Python字符串替换

时间:2020-03-05 15:29:18  来源:igfitidea点击:

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

.replace()方法

在Python中,字符串表示为不可变的“ str”对象。
'str'类带有许多允许我们操作字符串的方法。

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

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

该方法返回字符串'srt'的副本,其中子字符串'old'的部分或者全部匹配项被'new'替换。
如果未给出“ maxreplace”,则所有出现的事件都将被替换。

在下面的示例中,我们将字符串“ s”中的子字符串“ far”替换为“ 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.'

要删除子字符串,请使用空字符串“''代替。
例如,要从以下字符串中删除“空格”,请使用:

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