【问题标题】:Encoder for a string - Python字符串编码器 - Python
【发布时间】:2016-07-23 11:06:27
【问题描述】:

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

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

出于测试目的,我使用了函数调用: 首字母:

encode("blagh", {"a":"e","h":"r"})

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

encode("once upon a time",{'a':'ae','e':'ei','i':'io','o':'ou','u':'ua'})

对于上面的第二个,我正在寻找以下输出: 'ouncei uapoun ae tiomei'

但我发现自己有:

"ounceio uapoun aeio tiomeio"

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

【问题讨论】:

标签: python string loops dictionary encoding


【解决方案1】:

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

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

使用generator expression

def encode(msg, code):
    return ''.join(code.get(ch, ch) for ch in msg)

【讨论】:

    【解决方案2】:

    Python 3 的 str.translate 函数可以满足您的需求。请注意,翻译字典必须使用 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
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 2017-11-01
      • 1970-01-01
      • 1970-01-01
      • 2018-10-04
      • 2014-01-08
      • 2012-02-22
      相关资源
      最近更新 更多