替换 Python 字符串中的 '"' 字符

replacing a '"' character in a Python string

我要替换字符串中的几个字符。有些是按字母顺序排列的,并且完全按预期工作。但是我还需要替换一个双引号,但是失败了。

    str = 'this contains the " character'
    for r in (('"', 'quo'),('c', 'CC'), ('t', 'TT')):
        result = str.replace(*r)
    print(result)  # the " doesn't get replaced

我尝试使用 '\"' 而不是 '"' 但这没有区别。我在这里错过了什么?

您正在对 原始 字符串执行每个替换,而不是每个先前替换的结果。你需要像

这样的东西
s = 'this contains the " character'
result = s
for r in (('c', 'CC'), ('t', 'TT')):
    result = result.replace(*r)
print(result)  # works just fine