是否可以替换出现多次的字符串中的单个字符?
输入:
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
最佳答案
您可以通过包含一些上下文来做到这一点:
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
关于python - 替换 Python 3.1 中字符串中的重复字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/5412282/