Python Replace: How to Use replace() Function
In Python, you can use the replace() method to replace a specified substring within a string. The syntax of the replace() method is as follows:
str.replace(old, new, count)
In this case, “old” is the substring to be replaced, “new” is the new substring to replace it with, and “count” is an optional parameter used to specify the number of replacements. If the “count” parameter is not specified, all matching substrings will be replaced.
The sample code is as follows:
str = "Hello, World!"
new_str = str.replace("Hello", "Hi")
print(new_str) # 输出: Hi, World!
If you want to replace all matching substrings, you can omit the count parameter.
str = "apple, apple, orange, apple"
new_str = str.replace("apple", "banana")
print(new_str) # 输出: banana, banana, orange, banana