在本文中,我们将讨论如何在 Python 中使用replace()
method.
.replace() 方法#
在Python中,字符串被表示为不可变的str
对象。这str
类附带了许多允许您操作字符串的方法。
The .replace()
方法采用以下语法:
str.replace(old, new[, maxreplace])
-
str
- 您正在使用的字符串。
-
old
– 您要替换的子字符串。
-
new
– 替换旧子字符串的子字符串。
-
maxreplace
– 可选参数。您要替换的旧子字符串的匹配数。匹配项是从字符串的开头开始计数的。
该方法返回字符串的副本srt
与子字符串的部分或全部匹配old
取而代之new
. If maxreplace
未给出,所有出现的地方都将被替换。
在下面的示例中,我们将替换子字符串far
在字符串中s
with miles
:
s = 'A long time ago in a galaxy far, far away.'
s.replace('far', 'miles')
结果是一个新字符串:
'A long time ago in a galaxy miles, miles away.'
字符串文字通常用单引号括起来,但也可以使用双引号。
当可选的maxreplace
给出参数,它将限制替换匹配的数量。在以下示例中,我们仅替换第一次出现的位置:
s = 'My ally is the Force, and a powerful ally it is.'
s.replace('ally', 'friend', 1)
结果字符串将如下所示:
'My friend is the Force, and a powerful ally it is.'
要删除子字符串,请使用空字符串''
作为替代品。例如删除space
您可以使用以下字符串:
s = 'That’s no moon. It’s a space station.'
s.replace('space ', '')
新字符串将如下所示:
`That’s no moon. It’s a station.'
替换字符串列表中的子字符串#
替换a中的子字符串list字符串,使用列表理解构造,如下所示:
s.replace('old', 'new') for s in list
让我们看一下下面的例子:
names = ['Anna Grace', 'Betty Grace', 'Emma Grace']
new_names = [s.replace('Grace', 'Lee') for s in names]
print(new_names)
上面的代码创建了包含所有出现的子字符串的列表的副本Grace
取而代之Lee
:
['Anna Lee', 'Betty Lee', 'Emma Lee']
结论#
在Python中编写代码时,替换字符串中的子字符串是最基本的操作之一。阅读完本教程后,您应该对如何使用replace()
method.
如果您有任何问题或反馈,请随时发表评论。