在Python 3中替换重复字符

2 投票
3 回答
2749 浏览
提问于 2025-04-16 14:17

有没有办法替换一个字符串里面出现很多次的单个字符

输入:

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'

3 个回答

0

当然可以,不过你基本上需要把你想要的部分组合成一个新的字符串:

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

关于这里使用的符号说明,可以查看 Python切片符号的好入门

0

如果你知道自己想替换第一个出现的 x,还是第二个、第三个,或者最后一个,你可以把 str.find(如果想从字符串的末尾开始,可以用 str.rfind)和切片、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

4

你可以通过添加一些上下文来实现这个功能:

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

另外,你也可以保持一个不想替换的单词列表:

whitelist = ['example', 'explanation']

def replace_except_whitelist(m):
    s = m.group()
    if s in whitelist: return s
    else: return s.replace('x', 'i')

s = 'Thxs example'
result = re.sub("\w+", replace_except_whitelist, s)
print(result)

输出结果:

This example

撰写回答