Python替换字符串教程展示了如何在Python中替换字符串。
Python教程是Python语言的综合教程。
Python中有几种替换字符串的方法:
- replace方法
- re.sub方法
- translate方法
- 字符串切片和格式化
Python用replace方法替换字符串
replace方法返回字符串的副本,所有出现的子字符串旧的都替换为新的。
replace(old, new[, count])
参数是:
- old―要替换的旧子串
- new―替换旧子串的新子串。
- count―可选的计数参数决定如何许多出现被替换
#!/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方法。它以我们进行替换的字符串作为第一个参数。
#!/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字符串。
#!/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参数可用于仅替换给定单词的第一次出现。
#!/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”。
#!/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方法来进行多次替换。
#!/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方法允许替换字典中指定的多个字符。
#!/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方法返回通过用replacementrepl替换string中pattern的最左边非重叠出现而获得的字符串。
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.
我们有一个小文本文件。
#!/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教程或列出所有Python教程。
