用字典python中的值替换字符串中的多个字符 [英] replace multiple characters in string with value from dictionary python

查看:77
本文介绍了用字典python中的值替换字符串中的多个字符的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我试图创建一个遍历字符串的函数,在字典中找到与键匹配的字符,然后用字典中该键的值替换该字符.但是,它目前仅替换字典中出现的字母的第一个出现的字母,并在该处停止,这是我哪里出错了?

I'm trying to create a function that iterates through a string, finds characters that match to keys in a dictionary and replaces that character with the value in the dictionary for that key. However it currently only replaces first occurrence of a letter that is in the dictionary and stops there, where am I going wrong?

d = {
'I':'1', 'R':'2', 'E':'3', 'A':'4', 'S':'5', 'G':'6', 'T':'7', 'B':'8', 'O':'0',
'l':'1', 'z':'2', 'e':'3', 'a':'4', 's':'5', 'b':'6', 't':'7', 'g':'9', 'o':'0',
}

def cypher(string):
    for i in string:
        if i in d:
            a = string.replace(i,d[i])
            return a

推荐答案

您将在for循环中以对return的调用过早地结束代码.您可以通过在循环外存储新的字符串来修复它,只有在循环完成后才返回:

You are prematurely ending your code with the call to return within the for loop. You can fix it by storing your new string outside of the loop, only returning once the loop is done:

def cypher(string):
    a = string  # a new string to store the replaced string
    for i in string:
        if i in d:
            a = a.replace(i, d[i])
    return a

但是,逻辑也有问题.如果您的词典中的值也是词典中的键,则该键可能会被替换两次.例如,如果您有d = {'I': 'i', 'i': 'a'},并且输入是Ii,则输出将是aa.

There is something wrong about the logic too, though. If you have a value in your dictionary that is also a key in the dictionary, the key may get replaced twice. For example, if you have d = {'I': 'i', 'i': 'a'}, and the input is Ii, your output would be aa.

这是使用 join 更为简洁的实现没有这个问题.

Here's a much more concise implementation using join that does not have this problem.

def cypher(string):
    return ''.join(d.get(l, l) for l in string)

这篇关于用字典python中的值替换字符串中的多个字符的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆