Python - sys.stdin.readline() - 图书馆

Python - sys.stdin.readline() - library

import sys

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

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

它给我一个错误

Traceback (most recent call last): File "C:/some/random/dir/right/here/progr.py", line 9, in print(lijst_salades[input]) KeyError: 'truffelsalade\n'

谁能解释一下哪里做错了? 如果我使用 print(lijst_salades['Eiersalade'] 它工作正常。

问题是您读取 \n 字符时输入已通过,错误状态为:

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])

此外,建议对输入添加测试,因为如果键不存在,它也会引发类型为 KeyError 的错误。

编辑

您可以通过以下链接了解转义字符:

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

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