python - 从列表中取出字符并将它们变成其他字符

标签 python string python-3.x

我已经制作了一种 secret 语言,我可以将完整的单词放入输入中并获得列表中字母应该是的输出。比方说,我输入“AB”,我希望输出为“QW”。

while True:
    print("type sentence you want translated")
    Befor=input()
    After=list(Befor)

    if Befor=="A":
        print("Q")
    elif Befor=="B":
        print("W")
    elif Befor=="C":
        print("E")
    elif Befor=="D":
        print("R")
    else:
        print("--")

    print(After)

pass

最佳答案

您正在输入两个字母,但您的测试条件每个只包含一个字符。您应该使用 for 迭代输入字符串并一次测试字符串中的每个字符:

before = input()

for i in before:
    if i=="A":
        print("Q")
    elif i=="B":
        print("W")
    elif i=="C":
        print("E")
    elif i=="D":
        print("R")
    else:
        print("--")

您还可以通过使用映射 代替if/elif 来改进您的代码,因为这将帮助您更轻松地适应新的翻译:

before = input()
mapping = {'A': 'Q', 'B': 'W', 'C': 'E', 'D': 'R'}

after = ''.join(mapping.get(x, '--') for x in before)
print(after)

注意当映射不包含字符时,字典的 get 方法是如何返回默认的 '--' 的。

关于python - 从列表中取出字符并将它们变成其他字符,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40330896/

相关文章:

python-3.x - 使用 pandas 隐藏曲面图上的图例和比例信息,plotly

python-3.x - 通过重新定义 style.kv 自定义 Kivy 设置面板

r - 自动从列中提取拼写不匹配的字符串并在 R 中替换它们

c - 如何为 char 字符串中的位获取和设置位?

c - 一堆字符串

python - 如何检查 ansible 任务返回的数组中是否存在字符串

python-3.x - 如何使用 PyQt5 在 Qt 中显示数学排版(MathJax、LaTeX 等)?

python - 无法理解uniform_filter1d()函数的工作原理(从scipy.ndimage.filters导入)

python - 从调用脚本获取 __file__

python - 根据其内容将 numpy 数组拆分为类似的数组