current position:Home>Python string method tutorial - how to use the find() and replace() functions on Python strings

Python string method tutorial - how to use the find() and replace() functions on Python strings

2022-01-30 11:23:31 Dirubin

stay Python When processing strings in , You may need to search for a pattern in the string , Even replace part of the string with another substring .

Python There are useful string methods find() and replace() , Help us perform these string processing tasks .

In this tutorial , We'll look at these two string methods through sample code .

Python The immutability of strings

Python The string in is _ immutable _ Of . therefore , We can't _ In place _ Modify string .

Strings follow a zero index Python Iteratable terms . The length is n The valid index of the string is 0,1,2,..,(n-1) .

We can also use _ Negative index _, The index of the last element is -1 , The index of the penultimate element is -2 , And so on .

for example , We have my_string , There is a string "writer" . Let's try by setting the last character to "s" , Change it to "writes" .

my_string = "writer"
 Copy code 

Let's try to assign the last character to the letter "s" , As shown in the figure below . By negative index , We know my_string The index of the last character in 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 code 

This is shown in the code snippet above , We get a TypeError . This is because the string object is _ It can't be changed _ Of , The assignment we are trying to make is invalid .

However , We may often need to modify the string . The string method can help us do this easily .

String method pair _ The existing _ String operation , and _ Return to new _ Modified string . Existing string _ Can't _ Be modified .

Let's go to the next section to learn find() and replace() Method .

How to use find() stay Python Search pattern in string

You can use Python Of find() Method searches a string for a pattern . The general syntax is as follows .

<this_string>.find(<this_pattern>)
 Copy code 

The input string we want to search is composed of placeholders this_string It means . The pattern we want to search is composed of placeholders this_pattern .

Now let's analyze the above Syntax .

  • find() Methods by this_string Search for this_pattern Appearance .
  • If this_pattern There is , It will return this_pattern Of _ for the first time _ The starting index that appears .
  • If this_pattern Not in this_string in , It will return -1 .

Let's look at some examples .

Python find() Method example

Let's give you an example , character string "I enjoy coding in Python!" .

my_string = "I enjoy coding in Python!"
my_string.find("Python")

# Output
18
 Copy code 

In the example above , We try to be in "my_string" Mid search "Python" .find() Method returns 18 , That's the pattern "Python" The starting index of .

To verify that the returned index is correct , We can check my_string[18]=="P" 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 code 

In this case , We try to search for a string that does not exist in our string "JavaScript" .find() Method has returned -1 , As mentioned earlier .

How to use find() To search for Python Patterns in substrings

We can also use find() Method at some point _ Substring _ Or string _ fragment _ Search mode in , Not the whole string .

under these circumstances ,find() The call form of the method is as follows .

<this_string>.find(<this_pattern>, <start_index>,<end_index>)
 Copy code 

This is very similar to the grammar work discussed earlier .

The only difference is , The pattern search is not on the entire string . It's just start_index:end_index A of the specified string _ fragment _ On .

How to use index() To search for Python Pattern in string

To search for the occurrence of a pattern in a string , We might as well use index() Method . The method is called in the following syntax .

<this_string>.index(<this_pattern>)
 Copy code 

index() The method works with find() The method works very similar .

  • If this_pattern Exist in this_string in ,index() Method returns this_pattern Of _ for the first time _ The starting index that appears .
  • However , If this_pattern stay this_string Not found in , It will create a ValueError .

The example of time .

Python index() Examples of methods

Let's use the string in the previous example my_string = "I enjoy coding in Python!" .

my_string.index("Python")

# Output
18
 Copy code 

under these circumstances , Output and find() The output of the method is the same .

If we search for a substring that does not exist in our string ,index() Method will raise a ValueError . This is shown in the following code snippet .

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 code 

In the next section , We'll learn how to find and replace patterns in strings .

How to use replace() To find and replace Python Pattern in string

If you need to find a pattern in a string , And replace it with another pattern , You can use replace() Method . The general syntax is as follows .

<this_string>.replace(<this>,<with_this>)
 Copy code 

Now let's parse the syntax .

  • replace() Methods by this_string Search for this Pattern .
  • If this Mode of existence , It will return a new string , among _ all _ The emergence of this The mode is replaced by with_this The mode specified by the parameter .
  • If this Patterns in this_string Not found in , The string returned is the same as this_string identical .

If you want to replace only a certain number of occurrences , Not all patterns appear ?

under these circumstances , You can add a... To the method call _ Optional _ Parameters , Specify how many patterns you want to replace .

<this_string>.replace(<this>,<with_this>, n_occurrences)
 Copy code 

In the grammar above ,n_occurrences , Ensure that only the first of the pattern is replaced in the returned string n appear .

Let's look at some examples to understand replace() How functions work .

Python replace() Method example

Now let's redefine my_string , As shown below .

I enjoy coding in C++.
C++ is easy to learn.
I've been coding in C++ for 2 years now.:)
 Copy code 

This is shown in the following code snippet .

my_string = "I enjoy coding in C++.\nC++ is easy to learn.\nI've been coding in C++ for 2 years now.:)"

 Copy code 

Now let's use "Python" Replace all that appears "C++" , 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 code 

because replace() Method returns a string , We see in the output \n character . For the introduction of line breaks \n , We can print out strings , 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 code 

In the example above , We see all that appears "C++" It's all replaced by "Python" .

Now? , We also need to use additional n_occurrences Parameters .

The following code returns a string , among "C++" The first two occurrences of are replaced by "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 code 

The following code returns a string , Only for the first time "C++" Be replaced by "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 code 

Now? , We try to replace one in my_string Substring that does not exist in "JavaScript" . therefore , The string returned is the same as my_string identical .

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 code 

summary

In this tutorial , We learned the following .

  • How to use find() and index() Method in Python Search string in , as well as
  • How to use replace() Method to find and replace a pattern or substring .

I hope you like this tutorial .

I'll see you in another article soon . Until then, , I wish you all a happy study !


Bala Priya C

Bala Priya C

I read 、 Writing and coding


If this article helps you , Please post it on twitter .

Learn the code for free .freeCodeCamp Open source courses have helped more than 40,000 People get development jobs . Let's get started

copyright notice
author[Dirubin],Please bring the original link to reprint, thank you.
https://en.pythonmana.com/2022/01/202201301123297732.html

Random recommended