在python 2和3中使用input/raw_input [英] Use of input/raw_input in python 2 and 3
问题描述
我想设置一个带有以下问题的用户提示:
I would like to set a user prompt with the following question:
save_flag未设置为1;数据将不会保存.按Enter键继续.
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兼容?
input()
works in python3 but not python2. raw_input()
works in python2 but not python3. Is there a way to do this so that the code is compatible with both python 2 and python 3?
推荐答案
在Python 2中将raw_input
绑定到input
Bind raw_input
to input
in Python 2:
try:
input = raw_input
except NameError:
pass
现在input
也会在Python 2中返回一个字符串.
Now input
will return a string in Python 2 as well.
如果您使用 six
编写2/3兼容代码,则six.input()
在Python 2中更改为raw_input()
,在Python 3中更改为input()
.
If you're using six
to write 2/3 compatible code then six.input()
there points to raw_input()
in Python 2 and input()
in Python 3.
这篇关于在python 2和3中使用input/raw_input的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!