Skip to main content
 首页 » 编程设计

python之有没有办法接受 '%' 作为在 python 2.6 和 3.0 中都有效的输入的一部分

2024年08月12日31cloudgamer

在 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。