在python3.1中替换字符串中重复出现的字符

2024-10-04 07:29:11 发布

您现在位置:Python中文网/ 问答频道 /正文

是否可以替换字符串中多次出现的单个字符?在

输入:

Sentence=("This is an Example. Thxs code is not what I'm having problems with.") #Example input
                                 ^
Sentence=("This is an Example. This code is not what I'm having problems with.") #Desired output

"Thxs"中的“x”替换为i,而不替换"Example"中的x。在


Tags: 字符串aninputisexamplewithnotcode
3条回答

您可以通过包含一些上下文来实现:

s = s.replace("Thxs", "This")

或者,您可以保留一个您不想替换的单词列表:

^{2}$

输出:

This example

当然,但是你必须从你想要的部分中建立一个新的字符串:

>>> s = "This is an Example. Thxs code is not what I'm having problems with."
>>> s[22]
'x'
>>> s[:22] + "i" + s[23:]
"This is an Example. This code is not what I'm having problems with."

有关这里使用的符号的信息,请参见good primer for python slice notation。在

如果您知道要替换第一个出现的x,或者第二个,或者第三个,或者最后一个,那么您可以将str.find(或者{},如果您希望从字符串的末尾开始)与切片和str.replace结合使用,将要替换的字符输入到第一个方法中,以获得位置所需的次数为准在要替换的字符之前(对于您建议的特定句子,只替换一个),然后将字符串分成两部分,在第二个片段中只替换一个出现的字符。在

一个例子胜过千言万语,或者他们说的那样。在下面,我假设您想要替换这个字符的第(n+1)次出现。在

>>> s = "This is an Example. Thxs code is not what I'm having problems with."
>>> n = 1
>>> pos = 0
>>> for i in range(n):
>>>     pos = s.find('x', pos) + 1
...
>>> s[:pos] + s[pos:].replace('x', 'i', 1)
"This is an Example. This code is not what I'm having problems with."

请注意,您需要向pos添加偏移量,否则将替换刚刚找到的x的出现。在

相关问题 更多 >