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
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
nThe valid index of the string is
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
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
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
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
Now let's analyze the above Syntax .
this_patternThere is , It will return
this_patternOf _ for the first time _ The starting index that appears .
this_stringin , It will return
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
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=="P" Evaluated as
Now? , We will try to search for a substring that does not exist in our string .
In this case , We try to search for a string that does not exist in our string
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_indexA 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 .
this_patternOf _ for the first time _ The starting index that appears .
- However , If
this_stringNot found in , It will create a
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 .
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 .
thisMode of existence , It will return a new string , among _ all _ The emergence of
thisThe mode is replaced by
with_thisThe mode specified by the parameter .
this_stringNot found in , The string returned is the same as
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
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
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
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
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
my_string identical .
In this tutorial , We learned the following .
- How to use
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 !
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
author[Dirubin],Please bring the original link to reprint, thank you.
The sidebar is recommended
- Python Network Programming -- create a simple UPD socket to realize mutual communication between two processes
- leetcode 110. Balanced Binary Tree（python）
- Django uses Django celery beat to dynamically add scheduled tasks
- The bear child said "you haven't seen Altman" and hurriedly studied it in Python. Unexpectedly
- Optimization iteration of nearest neighbor interpolation and bilinear interpolation algorithm for Python OpenCV image
- Bilinear interpolation algorithm for Python OpenCV image, the most detailed algorithm description in the whole network
- Use of Python partial()
- Python game development, pyGame module, python implementation of angry birds
- leetcode 1104. Path In Zigzag Labelled Binary Tree（python）
- Save time and effort. 10 lines of Python code automatically clean up duplicate files in the computer
guess what you like
Learn python, know more meat, and be a "meat expert" in the technical circle. One article is enough
[Python data structure series] "stack (sequential stack and chain stack)" -- Explanation of knowledge points + code implementation
Datetime module of Python time series
Python encrypts and decrypts des to solve the problem of inconsistency with Java results
Chapter 1: introduction to Python programming-4 Hello World
Summary of Python technical points
11.5K Star！ An open source Python static type checking Library
Chapter 2: Fundamentals of python-1 grammar
[Python daily homework] day4: write a function to count the number of occurrences of each number in the incoming list and return the corresponding dictionary.
Python uses turtle to express white
- Some people say Python does not support function overloading?
- "Python instance" was shocked and realized the dirty words and advertisement detection of the chat system with Python
- Introduction to Python - CONDA common commands
- Python actual combat | just "4 steps" to get started with web crawler (with benefits)
- Don't know what to eat every day? Python to tell you! Generate recipes and don't worry about what to eat every day!
- Are people who like drinking tea successful? I use Python to make a tea guide! Do you like it?
- I took 100g pictures offline overnight with Python just to prevent the website from disappearing
- Binary operation of Python OpenCV image re learning and image smoothing (convolution processing)
- Analysis of Python event mechanism
- Iterator of Python basic language
- Base64 encryption and decryption in Python
- Chapter 2: Fundamentals of python-2 variable
- Python garbage collection summary
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (1)
- Python draws a spinning windmill with turtle
- Deep understanding of Python features
- A website full of temptations for Python crawler writers, "lovely picture network", look at the name of this website
- Python opencv Canny edge detection knowledge supplement
- Complex learning of Python opencv Sobel operator, ScHARR operator and Laplacian operator
- Python: faker extension package
- Python code reading (Part 44): find the location of qualified elements
- Elegant implementation of Django model field encryption
- 40 Python entry applet
- Pandas comprehensive application
- Chapter 2: Fundamentals of python-3 character string
- Python pyplot draws a parallel histogram, and the x-axis value is displayed in the center of the two histograms
- [Python crawler] detailed explanation of selenium from introduction to actual combat 
- Curl to Python self use version
- Python visualization - 3D drawing solutions pyecharts, Matplotlib, openpyxl
- Use python, opencv's meanshift and CAMSHIFT algorithms to find and track objects in video
- Using python, opencv obtains and changes pixels, modifies image channels, and trims ROI
- [Python data collection] university ranking data collection
- [Python data collection] stock information collection
- Python game development, pyGame module, python takes you to realize a magic tower game from scratch (2)
- Python solves the problem of suspending execution after clicking the mouse in CMD window (fast editing mode is prohibited)
- [Python from introduction to mastery] (II) how to run Python? What are the good development tools (pycharm)
- Python type hints from introduction to practice
- Python notes (IX): basic operation of dictionary
- Python notes (8): basic operations of collections
- Python notes (VII): definition and use of tuples