ZetCode

Python 替换字符串

最后修改于 2024 年 1 月 29 日

Python 替换字符串教程展示了如何在 Python 中替换字符串。

在 Python 中有几种替换字符串的方法

Python 使用 replace 方法替换字符串

replace 方法返回字符串的副本,其中所有出现的子字符串 old 都被 new 替换。

replace(old, new[, count])

参数为:

replacing.py
#!/usr/bin/python

msg = "There is a fox in the forest. The fox has red fur."

msg2 = msg.replace('fox', 'wolf')

print(msg2)

在这个例子中,所有出现的 'fox' 都被替换为 'wolf'。

$ ./replacing.py
There is a wolf in the forest. The wolf has red fur.

或者,我们可以使用 str.replace 方法。它将我们进行替换的字符串作为第一个参数。

replacing2.py
#!/usr/bin/python

msg = "There is a fox in the forest. The fox has red fur."

msg2 = str.replace(msg, 'fox', 'wolf')

print(msg2)

这个例子和前一个例子等价。


在下一个例子中,我们有一个 CSV 字符串。

replacing3.py
#!/usr/bin/python

data = "1,2,3,4,5,6,7,8,9,10"

data2 = data.replace(',', '\n')

print(data2)

将每个逗号替换为换行符。

$ ./replacing3.py
1
2
3
4
5
6
7
8
9
10
$ ./replacing3.py | awk '{ sum+=$1} END {print sum}'
55

Python 替换字符串的第一次出现

可以使用 count 参数只替换给定单词的第一次出现。

replacing_first.py
#!/usr/bin/python

msg = "There is a fox in the forest. The fox has red fur."

msg2 = msg.replace('fox', 'wolf', 1)

print(msg2)

这个例子替换了单词 'fox' 的第一次出现。

$ ./replace_first.py
There is a wolf in the forest. The fox has red fur.

Python 替换字符串的最后一次出现

在下一个例子中,我们替换单词 'fox' 的最后一次出现。

replace_last.py
#!/usr/bin/python

msg = "There is a fox in the forest. The fox has red fur."

oword = 'fox'
nword = 'wolf'
n = len(nword)

idx = msg.rfind(oword)
idx2 = idx + n - 1

print(f'{msg[:idx]}{nword}{msg[idx2:]}')

我们使用 rfind 方法找到消息中最后一次出现 'fox' 单词的索引。我们通过省略旧单词并在那里放置一个新单词来构建一个新字符串。 我们使用字符串切片和格式化操作。

$ ./replace_last.py
There is a fox in the forest. The wolf has red fur.

Python 链接 replace 方法

可以链接 replace 方法来执行多个替换。

chaining.py
#!/usr/bin/python

msg = "There is a fox in the forest. The fox has red fur."

msg2 = msg.replace('fox', 'wolf').replace('red', 'brown').replace('fur', 'legs')

print(msg2)

在这个例子中,我们执行了三个替换。

$ ./chaining.py
There is a wolf in the forest. The wolf has brown legs.

Python 使用 translate 替换字符

translate 方法允许替换字典中指定的多个字符。

translating.py
#!/usr/bin/python

msg = "There is a fox in the forest. The fox has red fur."

print(msg.translate(str.maketrans({'.': '!'})))

在这个例子中,我们用感叹号替换点字符。

$ ./translating.py
There is a fox in the forest! The fox has red fur!

Python 使用 re.sub 替换字符串

我们可以使用正则表达式来替换字符串。

re.sub(pattern, repl, string, count=0, flags=0)

re.sub 方法返回通过将字符串中最左边的非重叠 pattern 替换为 repl 而获得的字符串。

thermopylae.txt
The Battle of Thermopylae was fought between an alliance of Greek city-states,
led by King Leonidas of Sparta, and the Persian Empire of Xerxes I over the
course of three days, during the second Persian invasion of Greece.

我们有一个小文本文件。

replace_reg.py
#!/usr/bin/python

import re

filename = 'thermopylae.txt'

with open(filename) as f:

    text = f.read()


cleaned = re.sub('[\.,]', '', text)

words = set(cleaned.split())

for word in words:
    print(word)

我们读取文本文件并使用 re.sub 方法删除标点符号。我们将文本分割成单词并使用 set 函数获取唯一的单词。

cleaned = re.sub('[\.,]', '', text)

在本例中,我们文件中只有点号和逗号标点符号。 我们用空字符串替换它们,从而删除它们。

$ ./replace_reg.py
city-states
days
was
Empire
and
second
of
led
Battle
alliance
Greece
King
Persian
Leonidas
during
between
course
Thermopylae
Sparta
I
over
three
by
Xerxes
invasion
an
Greek
The
fought
the

来源

Python 语言参考

在本文中,我们已经在 Python 中替换了字符串。

作者

我叫 Jan Bodnar,是一位充满热情的程序员,拥有丰富的编程经验。 我自 2007 年以来一直在撰写编程文章。 迄今为止,我已经撰写了超过 1,400 篇文章和 8 本电子书。 我拥有超过十年的编程教学经验。

列出所有 Python 教程