Python Implement Simple String Replacement
In Python, string replacement is a common operation. We can use the str.replace() method to implement simple string replacement. This method replaces all matching substrings in a string with the specified new string.
Example
Raw strings
original_string
=
"Hello, world! Hello, Python!"
Use the replace() method to replace a string
new_string
=
original_string.
replace
(
"Hello"
,
"Hi"
)
Print the replaced string
(
new_string
)
Code analysis:
original_stringis the original string, with the content "Hello, world! Hello, Python!".original_string.replace("Hello", "Hi")Replace all "Hello" in the string with "Hi".new_stringis the new string after replacement.print(new_string)Print the replaced string.
Output result:
Hi, world! Hi, Python!
Python3 Examples