How can you replace a specific substring in a string using Python?

In Python, you can use the replace() method to substitute a string with another string.

The syntax of the replace() method is as follows:

string.replace(old, new, count)

In this case, “old” is the old string to be replaced, “new” is the new string to replace with, and “count” is an optional parameter indicating how many replacements to make (default is to replace all).

Here is an example:

string = "Hello, World!"
new_string = string.replace("World", "Python")
print(new_string)

The output results:

Hello, Python!

In this example, we are replacing the string “World” with “Python” and storing the result in a variable called new_string. Then, we print out the new string new_string.

Note that the replace() method returns a new string and does not modify the original string. If you need to replace in the original string, you can assign the result to the original string variable.

string = string.replace("World", "Python")
print(string)  # 输出结果为 "Hello, Python!"
bannerAds