在python 2和3中使用input / raw_input

时间:2014-02-12 14:40:58

标签: python python-3.x input python-2.x raw-input

我想用以下问题设置用户提示:

save_flag is not set to 1; data will not be saved. Press enter to continue.

input()适用于python3但不适用于python2。 raw_input()适用于python2,但不适用于python3。有没有办法做到这一点,以便代码兼容python 2和python 3?

6 个答案:

答案 0 :(得分:49)

在Python 2中将raw_input绑定到input

try:
    input = raw_input
except NameError:
    pass

现在input也会在Python 2中返回一个字符串。


如果您使用six编写2/3兼容代码,则six.input()指向Python 2中的raw_input()和Python 3中的input()

答案 1 :(得分:5)

更新:此方法仅在您将来安装并且上述答案更好且更通用时才有效。

this cheatsheet开始,还有另一种看起来更干净的方法:

# Python 2 and 3:
from builtins import input

答案 2 :(得分:5)

我认为最好的方法是

nth-of-type

......它可以在2和3之间工作。

答案 3 :(得分:1)

这是因为,在python 2中,raw_input()接受给予stdin的所有内容,作为字符串,其中input()保留给定参数的数据类型(即,如果给定的参数是类型的int,然后它将仅保留为int,但不会像string那样转换为raw_input()。基本上,当使用input()时,它将stdin中提供的参数作为字符串,并对其进行求值。此评估将参数转换为相应的类型。

# Python 2.7.6
>>> a = raw_input("enter :- ")
enter :- 3
>>> type(a)     # raw_input() converts your int to string
<type 'str'>
>>> a = input("enter :- ")
enter :- 3
>>> type(a)    # input() preserves the original type, no conversion     
<type 'int'> 
>>>

因此,在Python 2中使用input()时,用户在传递参数时必须小心。如果要传递一个字符串,则需要使用quote传递它(因为python将quote中的字符识别为字符串)。否则NameError将被抛出。

 >>> a = input("enter name :- ")
 enter name :- Derrick
 Traceback (most recent call last):
 File "<stdin>", line 1, in <module>
 File "<string>", line 1, in <module>
 NameError: name 'Derrick' is not defined
 >>> a = input("enter name :- ")
 enter name :- 'Derrick'
 >>> a
 'Derrick'

然而,如果使用raw_input(),则在将参数作为字符串接受的所有内容传递时,您无需担心数据类型。但是,在您的代码中,您需要处理适当的类型转换。

为了避免Python 2中input()所需的额外关注,它已在Python 3中删除。raw_input()已在Python 3中重命名为input()。{的功能来自Python 2的{1}}已不再适用于Python 3. {3}}在Python 3中提供input()在Python 2中的服务。

This post可能有助于详细了解。

答案 4 :(得分:1)

明确加载函数:

from builtins import input

然后你可以在python2和python3中使用input()

您可能必须安装依赖项:

pip install future

答案 5 :(得分:1)

您可以在python2中编写代码并使用futurize或在python3中使用pasteurize。 这消除了考虑兼容代码的复杂性并保证了良好实践。

关于这个具体问题

from builtins import input

正是以上脚本产生的内容。