温馨提示×

python如何替换字符串的内容

小亿
78
2023-10-31 16:25:45
栏目: 编程语言

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!

0