When working with strings in Python, you may need to search for a pattern in the string, or even replace part of the string with another substring.
Python has useful string methods find() and replace() to help us perform these string processing tasks.
In this tutorial, we’ll look at both string methods through sample code.
Immutability of Python strings
Strings in Python are _ immutable _. Therefore, we cannot modify strings _ in place _.
Strings are Python iterable items that follow a zero index. Valid indexes for strings of length n are 0,1,2,.. And (n – 1).
We can also use the _ negative index _, with the last element having an index of -1, the second-to-last element having an index of -2, and so on.
For example, we have my_string, which holds the string “writer”. Let’s try changing it to “writes” by setting the last character to “s”.
my_string = "writer"
Copy the code
Let’s try assigning the last character to the letter “s”, as shown below. Using a negative index, we know that the index of the last character in my_string is -1.
my_string[-1] ="s"
# Output
---------------------------------------------------------------------------
TypeError Traceback (most recent call last)
<ipython-input-1-670491032ba6> in <module>()
1 my_string = "writer"
----> 2 my_string[-1] ="s"
TypeError: 'str' object does not support item assignment
Copy the code
As shown in the code snippet above, we get a TypeError. This is because the string object is _ immutable _, and the assignment we are trying to make is invalid.
However, we may often need to modify strings. The string method makes it easy to do this.
The string method operates on the _ existing _ string and returns the new _ modified string. The existing string _ will not be modified.
Let’s move on to the find() and replace() methods in the next section.
How do I use find() to search for patterns in Python strings
You can use Python’s find() method to search for a pattern in a string. The general syntax is as follows.
<this_string>.find(<this_pattern>)
Copy the code
The input string we want to search for is represented by the placeholder this_string. The pattern we want to search for is by placeholder this_pattern.
Now let’s parse the above syntax.
find()
Methods bythis_string
searchthis_pattern
The emergence of.- if
this_pattern
If yes, it will returnthis_pattern
The initial index of the first occurrence of. - if
this_pattern
Not present atthis_string
, it will return- 1
。
▶ Let’s take a look at some examples.
Example Python find() method
Let’s take an example of the string “I enjoy coding in Python!” .
my_string = "I enjoy coding in Python!"
my_string.find("Python")
# Output
18
Copy the code
In the example above, we tried to search for “Python” in “my_string”. The find() method returns 18, the starting index of the pattern “Python”.
To verify that the index returned is correct, we can check that my_string[18]==”P” is evaluated as True.
Now we will try to search for a substring that does not exist in our string.
my_string.find("JavaScript")
# Output
-1
Copy the code
In this example, we are trying to search for “JavaScript” that does not exist in our string. The find() method already returns -1, as mentioned earlier.
How do I use find() to search for patterns in Python substrings
We can also use the find() method to search for patterns in an _ substring _ or a _ fragment _ of a string, rather than the entire string.
In this case, the find() method is called as follows.
<this_string>.find(<this_pattern>, <start_index>,<end_index>)
Copy the code
This is very similar to the syntactic work discussed earlier.
The only difference is that the search for patterns is not on the entire string. It is just a _ fragment _ of the string specified by start_index:end_index.
How do I use index() to search for patterns in Python strings
To search for the occurrence of a pattern in a string, use the index() method. The method is called using the syntax shown below.
<this_string>.index(<this_pattern>)
Copy the code
The index() method works very similar to the find() method.
- if
this_pattern
Exists in thethis_string
,index()
Method returnsthis_pattern
The initial index of the first occurrence of. - However, if
this_pattern
在this_string
If it doesn’t find one, it produces oneValueError
。
▶ Time example.
Example of the Python index() method
Let’s use the string my_string = “I enjoy coding in Python!” from the previous example. .
my_string.index("Python")
# Output
18
Copy the code
In this case, the output is the same as that of the find() method.
If we search for a substring that does not exist in our string, the index() method raises a ValueError. This is shown in the code snippet below.
my_string.index("JavaScript")
# Output
---------------------------------------------------------------------------
ValueError Traceback (most recent call last)
<ipython-input-4-377f7c374e16> in <module>()
----> 1 my_string.index("JavaScript")
ValueError: substring not found
Copy the code
In the next section, we’ll learn how to find and replace patterns in strings.
How do I use replace() to find and replace patterns in Python strings
If you need to find a pattern in a string and replace it with another pattern, you can use the replace() method. The general syntax is as follows.
<this_string>.replace(<this>,<with_this>)
Copy the code
Let’s now parse this syntax.
replace()
Methods bythis_string
searchthis
Mode.- if
this
The pattern exists, and it will return a new string in which _ all _ appearsthis
The mode is replaced bywith_this
Parameter specifies the mode. - if
this
Patterns inthis_string
Is not found in, returns a string andthis_string
The same.
What if you wanted to replace only a certain number of occurrences, rather than all patterns?
In this case, you can add an optional _ argument to the method call specifying how many patterns you want to replace.
<this_string>.replace(<this>,<with_this>, n_occurrences)
Copy the code
In the syntax above, n_occurrences ensures that only the first n occurrences of the pattern are replaced in the returned string.
▶ Let’s look at some examples to see how the replace() function works.
Example Python Replace () method
Now let’s redefine my_string as follows.
I enjoy coding in C++.
C++ is easy to learn.
I've been coding in C++ for 2 years now.:)
Copy the code
This is shown in the code snippet below.
my_string = "I enjoy coding in C++.\nC++ is easy to learn.\nI've been coding in C++ for 2 years now.:)"
Copy the code
Now let’s replace all occurrences of “C++” with “Python”, like this.
my_string.replace("C++"."Python")
# Output
'I enjoy coding in Python.\nPython is easy to learn.\nI've been coding in Python for 2 years now.:)'
Copy the code
Since the replace() method returns a string, we see the \n character in the output. For \n with a newline, we can print out a string, as shown in the figure below.
print(my_string.replace("C++"."Python"))
# Output
I enjoy coding in Python.
Python is easy to learn.
I've been coding in Python for 2 years now.:)
Copy the code
In the example above, we see that all occurrences of “C++” are replaced with “Python”.
▶ Now, we’ll also use the additional n_occurrences parameter.
The following code returns a string in which the first two occurrences of “C++” are replaced with “Python”.
print(my_string.replace("C++"."Python".2))
# Output
I enjoy coding in Python.
Python is easy to learn.
I've been coding in C++ for 2 years now.:)
Copy the code
The following code returns a string in which only the first occurrence of “C++” is replaced with “Python”.
print(my_string.replace("C++"."Python".1))
# Output
I enjoy coding in Python.
C++ is easy to learn.
I've been coding in C++ for 2 years now.:)
Copy the code
Now we try to replace a substring “JavaScript” that does not exist in my_string. Therefore, the string returned is the same as my_string.
print(my_string.replace("JavaScript"."Python"))
# Output
I enjoy coding in C++.
C++ is easy to learn.
I've been coding in C++ for 2 years now.:)
Copy the code
conclusion
In this tutorial, we learned the following.
- How to use
find()
和index()
Method to search for strings in Python, as well - How to use
replace()
Method to find and replace patterns or substrings.
Hope you enjoyed this tutorial.
See you soon in another article. Until then, have fun!
Bala Priya C
I read, write and code
If this article has been helpful to you, please tweet it.
Learn code for free. FreeCodeCamp’s open source courses have helped more than 40,000 people land development jobs. Let’s start