字符串的编码器-Python

字符串的编码器-Python,python,string,loops,dictionary,encoding,Python,String,Loops,Dictionary,Encoding,我一直在用字典对随机字符串集进行编码。我已经用我的代码替换了我想要的字母,但在某些情况下,它会多次替换一个字符,而实际上我只希望它替换字符串中的字母一次。这就是我所拥有的: def encode(msg,code): for i in msg: for i in code: msg = msg.replace(i, code[i]) return msg 出于测试目的,我使用了函数调用: 首字母: 还有一个更复杂的字符串: enc

我一直在用字典对随机字符串集进行编码。我已经用我的代码替换了我想要的字母,但在某些情况下,它会多次替换一个字符,而实际上我只希望它替换字符串中的字母一次。这就是我所拥有的:

def encode(msg,code):
    for i in msg:
        for i in code:
            msg = msg.replace(i, code[i])
        return msg
出于测试目的,我使用了函数调用: 首字母:

还有一个更复杂的字符串:

encode("once upon a time",{'a':'ae','e':'ei','i':'io','o':'ou','u':'ua'})
对于上面的第二个,我正在寻找以下输出: “ouncei uapoun ae tiomei”

但我发现自己有:

“ounceio Uaboun aeio tiomeio”


如何将循环限制为只替换每个字符一次?

使用
str.replace
,而是逐个字符替换:

def encode(msg, code):
    result = ''
    for ch in msg:
        result += code.get(ch, ch)
    return result
使用:

Python3的函数可以满足您的需要。请注意,翻译词典必须对键使用Unicode序号,因此该函数使用词典理解将其转换为正确的格式:

def encode(msg,code):
    code = {ord(k):v for k,v in code.items()}
    return msg.translate(code)

print(encode("blagh", {"a":"e","h":"r"}))
print(encode("once upon a time",{'a':'ae','e':'ei','i':'io','o':'ou','u':'ua'}))
输出:

blegr
ouncei uapoun ae tiomei
如果使用Unicode字符串或在文件顶部添加以下内容以使字符串默认为Unicode,则它在Python 2中也可以工作:

from __future__ import unicode_literals
blegr
ouncei uapoun ae tiomei
from __future__ import unicode_literals