Translate/Replace 多个字母 Python

Translate/Replace Multiple Letters With Python

我正在开发一个非常基础的翻译程序。目前它只能处理一个短语中的一个字母。例如,如果我输入 "test",它会脱口而出 "yesy",因为它会将 "t" 更改为 "y"。这是我用来执行此操作的代码:

def translate(phrase):
    translation = ""
    for letter in phrase:
        if letter in "t":
            translation = translation + "y"
        else:
            translation = translation + letter
    return translation




print(translate(input("Enter word: ")))

是否可以添加另一个要翻译的字母。因此,例如 "e" 到 "a" 在 "t" 到 "y" 之上。这样它就会吐出"yasy"。

使用 str.replace 有一个更简单的方法:'test'.replace('t','y').replace('e','a')

但是,如果您要替换越来越多的字母,str.translate 会更有效率:

from string import maketrans

trans_from = "te"
trans_to = "ya"
trans_model = maketrans(trans_from, trans_to)

'test'.translate(trans_model)

或者,如果您想保留您的代码,您可以使用 elif:

def translate(phrase):
    translation = ""
    for letter in phrase:
        if letter in "t":
            translation = translation + "y"
        elif letter in "e":
            translation = translation + "a"
        else:
            translation = translation + letter
    return translation

print(translate(input("Enter word: ")))

使用字典。

en-gb = {'t':'y', add more here}
def translate(phrase): 
    translation = str()
    for char in phrase:
        translation = translation +   en-gb[char]
    return translation