python - 替换 Python 3.1 中字符串中的重复字符

标签 python string variables replace

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

输入:

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/

相关文章:

python - 如何在mongoengine stringfield中返回选择值

带有单个等号 (=) 的 Python while 循环

Javascript:变量值在回调中使用之前发生变化

mysql - 在过程中使用变量值创建 MySQL 查询

php - 在回显字符串中插入一个变量

python - 替换为 SymPy 中的多个子表达式

python - 为什么我收到错误消息 : list index out of range in Python

java - 为什么数组的第一个单元格中存储了一个空空间?

java - 如何使用图形在多行上输出一个字符串

c# - 如何有效地确定字符串是否以数字开头,然后获取所有后续数字,直到第一个非数字字符?