在 2.6 中,如果我需要接受允许百分号的输入(例如“foo % bar”),我使用 raw_input()
,它按预期工作。
在 3.0 中,input()
完成了相同的任务(raw_input() 已离开建筑物)。
作为练习,我希望能够有一个向后兼容的版本,可以与 2.6 和 3.0 一起使用。
当我在2.6中使用input()并输入“foo % bar”时,返回以下错误:
File "<string>", line 1, in <module>
NameError: name "foo" is not defined
...这是预期的。
无论如何要完成接受包含在 2.6 和 3.0 中都有效的百分号的输入吗?
谢谢。
最佳答案
您可以使用sys.version_info
来检测正在运行的Python版本。
import sys
if sys.version_info[0] == 2:
input = raw_input
# Now you can use
input()
或者,如果您不想覆盖 Python 2.X 的内置 input
函数,您可以编写
import sys
if sys.version_info[0] == 2:
my_input = raw_input
else:
my_input = input
# Now you can use
my_input()
尽管如此,即使在我的第一个代码示例中,原始的内置 input
始终可用作 __builtins__.input
。
关于python - 有没有办法接受 '%' 作为输入的一部分,在 python 2.6 和 3.0 中都有效?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/3058649/