Home >Backend Development >Python Tutorial >How to replace the contents of a string in python

How to replace the contents of a string in python

WBOY
WBOYforward
2024-03-01 22:55:02893browse

How to replace the contents of a string in python

pythonYou can use the replace() function to replace the contents of the string. replace()The function accepts two parameters. The first parameter is the string to be replaced, and the second parameter is the string to be replaced. Examples are as follows:

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

The output result is:

Hello, Python!

Note that the replace() function returns the new string after replacement, and the original string will not be modified. If you want to perform a replacement on the original string, you can assign it directly to the original string variable. For example:

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

The output result is:

Hello, Python!

The above is the detailed content of How to replace the contents of a string in python. For more information, please follow other related articles on the PHP Chinese website!

Statement:
This article is reproduced at:lsjlt.com. If there is any infringement, please contact admin@php.cn delete