好的,我一直在编写一个脚本,但是输入部分发生了一件烦人的事情。根据我拥有的 python 版本,我要么需要为我的输入包含引号,要么不需要。使用 python 2.7,我需要引号;使用 python 3.3,我没有。例如:
filename = input('Enter Update File: ')
print(filename)
使用 python 2.7,我需要用引号括起我的输入,否则会引发 NameError;在 python 3.3 中,我没有。
有没有办法避免这种情况?
好的,我一直在编写一个脚本,但是输入部分发生了一件烦人的事情。根据我拥有的 python 版本,我要么需要为我的输入包含引号,要么不需要。使用 python 2.7,我需要引号;使用 python 3.3,我没有。例如:
filename = input('Enter Update File: ')
print(filename)
使用 python 2.7,我需要用引号括起我的输入,否则会引发 NameError;在 python 3.3 中,我没有。
有没有办法避免这种情况?
在 Python 2.x 上,您需要使用raw_input()
而不是input()
. 在旧版本的 Python 中,input()
实际上将您键入的内容作为 Python 表达式求值,这就是您需要引号的原因(就像您在 Python 程序中编写字符串一样)。
Python 3.x 和 Python 2.x 有很多不同之处;这只是其中之一。但是,您可以使用如下代码解决此特定差异:
try:
input = raw_input
except NameError:
pass
# now input() does the job on either 2.x or 3.x