【发布时间】:2015-07-24 19:33:46
【问题描述】:
Python 3.2
这可能真的很愚蠢,但是:
items = {'1': 'ACK', '2': 'RELQ', '3': 'COM'}
choice = input('Choose an option:\n1.ACK\n2.RELQ\n3.COM\n')
print(choice)
if choice in items:
print(choice)
option = items[choice]
else:
print('Input not recognized')
如果你输入 1,它会一直返回
1
Input not recognized
choice in items 返回的是 false?
这应该很容易,但我就是看不到它是什么。
更新:
print(type(choice))` returns str
print(len(choice)) returns 2
print(repr(choice)) returns '1\r'
print(choice[0]) returns 1
输入正在接收带有 input() 的 \r 换行符
【问题讨论】:
-
这段代码对我有用,运行windows 8 64 bit python 3.4(.1) with IDLE。
-
好吧,它根本不适合我。我什至使用
print(type(choice))检查了类型,它返回了str。 -
检查
len(choice)。它可能在某处抓取了一个额外的字符 -
我的意思是,您使用的运行设置与我的运行设置有何不同。我知道由于
\r而不是\n的使用,字符串比较在 Mac 上会变得不稳定 -
不错,
print(len(choice))返回2它在哪里抓取了这个额外的字符?
标签: python if-statement semantics