Private archive copy · Unofficial site · Content copyright belongs to Runoob Tutorial and the original authors · View Original

Python Implement Simple String Replacement

Python Implement Simple String Replacement

Document Object Reference Manual Python3 Examples

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

print

(

new_string

)

Code analysis:

  1. original_string is the original string, with the content "Hello, world! Hello, Python!".
  2. original_string.replace("Hello", "Hi") Replace all "Hello" in the string with "Hi".
  3. new_string is the new string after replacement.
  4. print(new_string) Print the replaced string.

Output result:

Hi, world! Hi, Python!

Document Object Reference Manual Python3 Examples