使用字典中的keyvalue转换字符串

2021-08-02 16:18:53 发布

您现在位置:Python中文网/ 问答频道 /正文

此函数将字典作为参数并翻译给定的字符串。然而,它却成了一个无休止的循环。我一辈子都想不出如何让它正常工作。例如:它应该接受字符串“hi”并将其转换为“[-]1”

def translate(glyphs):
    string = input("Enter string to be translated: ").strip()
    new = ''
    for keys in glyphs:
        ind = string.upper().find(keys)
        while ind != -1: #while there exists a key in the string
            if len(glyphs[string[ind].upper()]) > 1: #if there is more than one value for key
                rand = randint(0, 1) #choose randomly
                transChar = glyphs[keys][rand]
                new = string[:ind] + transChar + string[ind+1:]
                ind = string.upper().find(keys)
                print("hi1")
            else:
                transChar = glyphs[keys][0]
                new = string[:ind] + transChar + string[ind+1:]
                ind = string.upper().find(keys)
                print("hi")
    return new

任何帮助都将不胜感激!