Python-sys.stdin.readline()-库

import sys

lijst_salades = {'Eiersalade' : 5.99,
                 'Paprikasalade' : 6.05,
                 'truffelsalade': 3.99
                 }

input = (sys.stdin.readline())
print(lijst_salades[input])

它给我一个错误

追溯(最近一次通话):文件   “ C:/some/random/dir/right/here/progr.py”,第9行,在       print(lijst_salades [input])KeyError:'truffelsalade \ n'

Can someone explain what is did wrong? If I use print(lijst_salades['Eiersalade'] it works fine.

评论
薄荷情
薄荷情

The problem is that you read the \n char with the input passed, as the error state:

KeyError:“ truffelsalade \ n”

您应该将代码修复为:

import sys

lijst_salades = {'Eiersalade' : 5.99,
                 'Paprikasalade' : 6.05,
                 'truffelsalade': 3.99
                 }

input = (sys.stdin.readline()).rstrip()
print(lijst_salades[input])

Also, it is advised to add a testing to the input, because if the key doesn't exist it will also raise an error of type KeyError.

编辑

您可以在以下链接中了解转义字符:

https://linuxconfig.org/list-of-python-escape-sequence-characters-with-examples

https://docs.python.org/2.0/ref/strings.html

点赞
评论