Python Simple String Replacement
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)
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:
original_stringis the original string, with content "Hello, world! Hello, Python!".original_string.replace("Hello", "Hi")Replace all occurrences of "Hello" in the string with "Hi".new_stringis the new string after replacement.print(new_string)Output the replaced string.
Output result:
Hi, world! Hi, Python!Other Extensions
Python3 Examples