首页 > 文章列表 > 如何使用Python替换字符串中的文本

如何使用Python替换字符串中的文本

Python 精选
462 2025-02-14

python如何替换字符串的内容

python中可以使用replace()函数来替换字符串的内容。replace()函数接受两个参数,第一个参数是要被替换的字符串,第二个参数是要替换成的字符串。示例如下:

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

输出结果为:

Hello, Python!

注意,replace()函数返回的是替换后的新字符串,原始字符串不会被修改。如果想要在原始字符串上进行替换,可以直接赋值给原始字符串变量。例如:

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

输出结果为:

Hello, Python!