如何处理此代码输出中的空格?

时间:2013-08-15 01:29:34

标签: python python-3.x iteration

首先,这是代码:

    alphabet = input("Please input the scrambled alphabet in order: ")
    message = input("Now input the scrambled message: ")
    secret_map = {}
    for index, letter in enumerate(alphabet):
        secret_map[letter] = chr(65 + index)
    new_str = ("".join([secret_map[char] for char in message]))
    print(new_str, end="")

OUTPUT
Please input the scambled alphabet in order = DRLOWNUKSBZQJHCTXMIFYGPAEV
Now input the scrambled message = LOWNUK
CDEFGH

但是

Please input the scambled alphabet in order = DRLOWNUKSBZQJHCTXMIFYGPAEV
Now input the scrambled message = LOWNUK LOWNUK
OUTPUT = 

    Traceback (most recent call last):
      File "/Users/sanjith/Documents/assign8t.py", line 6, in <module>
        new_str = ("".join([secret_map[char] for char in message]))
      File "/Users/sanjith/Documents/assign8t.py", line 6, in <listcomp>
        new_str = ("".join([secret_map[char] for char in message]))
    KeyError: ' '

我无法获得空间。我知道这与ascii number 32(之前的127改为)有关。

1 个答案:

答案 0 :(得分:0)

使用dict.get()

secret_map.get(char, char)