Python 中的字符串替换

在本文中,我们将讨论在 Python 中如何使用 replace() 方法替换字符串。

.replace()方法

在 Python 中,字符串表示为不可变的 str 对象。 str 对象配备了许多方法,让你操作字符串。

.replace() 方法采用以下语法:

str.replace(old, new[, maxreplace])
  • str - 您正在使用的字符串。
  • old – 您要替换的子字符串。
  • new – 替换旧子字符串的子字符串。
  • maxreplace – 可选参数。您要替换的旧子字符串的匹配数。匹配从字符串的开头开始计算。

该方法返回字符串 srt 的副本,其中子字符串 old 的某些或全部匹配项替换为 new 。如果 maxreplace 未给出,则替换所有出现的事件。

在下面的例子中,我们要使用 miles 替换字符串 s 中的子字符串 far

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.'

替换字符串列表中的子字符串

要替换字符串列表中的子字符串,请使用列表构造,如下所示:

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() 方法有很好的了解。