What is the purpose of the replace function in Python?
The replace function in Python is used to replace specific characters or substrings in a string. It takes two parameters: the character or substring to be replaced (first parameter) and the character or substring to replace it with (second parameter). This function will search for all instances of the first parameter in the string and replace them with the second parameter. It returns a new string and does not alter the original string.
For example:
string = "Hello, World!"
new_string = string.replace("World", "Python")
print(new_string) # 输出:Hello, Python!
In the example above, the replace function replaces “World” with “Python” in the string and returns the new string as “Hello, Python!”. The original string “Hello, World!” remains unchanged.