新闻资讯

质量为本、客户为根、勇于拼搏、务实创新

< 返回新闻资讯列表

python中如何用replace替换多个字符,python中如何用if语句

发布时间:2023-10-16 23:27:58

python中如何用replace替换多个字符

可使用replace()函数来替换多个字符。replace()函数接受两个参数,第一个参数是要被替换的字符(或字符组合),第二个参数是替换后的字符(或字符组合)。
下面是一个例子,演示怎样用replace()函数替换单个字符:

string = "Hello World"
new_string = string.replace("o", "e")
print(new_string)

输出结果为:

Helle Werld

如果要替换多个字符,可以屡次调用replace()函数。例如,想要将字符串中的字母o、r和l替换为字母e,可以这样写:

string = "Hello World"
new_string = string.replace("o", "e").replace("r", "e").replace("l", "e")
print(new_string)

输出结果为:

Heee Weed

注意:replace()函数返回一个新的字符串,原始字符串并没有改变。如果需要修改原始字符串,可以将替换后的结果赋值给原始字符串变量。