新闻资讯

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

< 返回新闻资讯列表

python字符串replace如何使用,python字符串replace方法

发布时间:2023-11-09 01:24:43

python字符串replace如何使用

Python中的字符串replace()方法用于将字符串中的某个子字符串替换为另外一个字符串。它的语法以下:

string.replace(old, new[, count])

其中,old表示要被替换的子字符串,new表示用于替换的新字符串。可选参数count表示替换的次数,如果不指定该参数,则默许替换所有出现的子字符串。

下面是一些使用示例:

string = "Hello, World!"

# 将字符串中的逗号替换为句号
new_string = string.replace(",", ".")

print(new_string)  # Output: Hello. World!

# 替换所有出现的o为a
new_string = string.replace("o", "a")

print(new_string)  # Output: Hella, Warld!

# 替换前两个出现的l为z
new_string = string.replace("l", "z", 2)

print(new_string)  # Output: Hezzo, World!

注意:replace()方法返回一个新的字符串,原始字符串不会遭到改变。如果需要替换原始字符串,可以将新字符串赋值给原始字符串变量。