Python Simple String Replacement

Document 对象参考手册Python3 Examples

In Python, string replacement is a common operation. We can usestr.replace()method to implement simple string replacement functionality. This method replaces all matching substrings in the string with the specified new string.

Example

# Original string
original_string = "Hello, world! Hello, Python!"

# Use the replace() method to replace the string
new_string = original_string.replace("Hello", "Hi")

# Output the replaced string
print(new_string)

Code explanation:

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

Output result:

Hi, world! Hi, Python!

Document 对象参考手册Python3 Examples

Other Extensions