Python之line.replace
文章目录
在Python中,
str.replace()
方法用于替换字符串中的一个或多个指定值。
基本语法是:
str.replace(old, new[, count])
其中:
old
:必需,需要被替换的子字符串。new
:必需,用于替换old
子字符串的新子字符串。count
:可选,指定了替换操作的次数。如果指定了该参数,只有old
子字符串中的前count
个子字符串会被替换。
例如:
text = "Hello, world!"
new_text = text.replace("world", "Python")
print(new_text) # 输出 "Hello, Python!"
如果你不指定 count
参数,那么所有的 old
子字符串都会被替换。例如:
text = "Hello, world! world!"
new_text = text.replace("world", "Python")
print(new_text) # 输出 "Hello, Python! Python!"
以下是一个指定 count
参数的例子:
text = "Hello, world! world!"
new_text = text.replace("world", "Python", 1)
print(new_text) # 输出 "Hello, Python! world!"
在这个例子中,我们指定了 count
参数为 1,表示只替换第一个出现的 "world"
子字符串。因此,第二个 "world"
子字符串没有被替换。