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

2024-03-29 10:15:55 发布

您现在位置: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

任何帮助都将不胜感激!


Tags: key字符串innewforstringkeysfind
1条回答
网友
1楼 · 发布于 2024-03-29 10:15:55

看起来您的字典包含可能的翻译列表作为值,您可以从中进行随机选择,以及大写键。这个列表应该有用,那么:

import random

new = ' '.join(random.choice(glyphs[word]) \
               for word in input_string.upper().split())

相关问题 更多 >