python - 在 Python 中使用字典替换字符串中的字符

标签 python dictionary replace character

我已经研究过使用字典进行字符替换,但我仍然无法让我的代码正常工作。我的代码是这样的:

def encode(code,msg):  
    for k in code:  
        msg = msg.replace(k,code[k])  
    return msg

现在,当我运行代码时:

code = {'e':'x','x':'e'}
msg = "Jimi Hendrix"
encode(code,msg)

它给了我“Jimi Hxndrix”而不是“Jimi Hxndrie”。如何将字母“x”也替换为“e”?

最佳答案

您可以查看 str.translate 或执行以下操作:

''.join(code.get(ch, ch) for ch in msg)

关于python - 在 Python 中使用字典替换字符串中的字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/13626728/

相关文章:

python - 为什么每次保存模型时哈希值都会改变?

python - SWIG 在 Windows 中生成 C++ Python3 包装器导致断言 MSVC 2017

python - 使用有序字典解析 xml 文件

python - 通过拆分键对字典进行排序

python - 从字典列表中的字典列表中删除重复项

python - 属性错误: 'Series' object has no attribute 'org' when trying to filter a dataframe

python - 使用来自另一个数据框的匹配值列表创建数据框列

javascript - 使用 javascript 替换替换 p 标签中的所有字符

python - 互相替换字符串内容

php - 如何使用 PHP ereg_replace 替换所有特定字符?