218*_*218 40 python input python-2.x raw-input python-3.x
我想用以下问题设置用户提示:
save_flag is not set to 1; data will not be saved. Press enter to continue.
Run Code Online (Sandbox Code Playgroud)
input()适用于python3但不适用于python2.raw_input()适用于python2但不适用于python3.有没有办法做到这一点,以便代码兼容python 2和python 3?
Ash*_*ary 51
绑定raw_input到input在Python 2:
try:
input = raw_input
except NameError:
pass
Run Code Online (Sandbox Code Playgroud)
现在input也将在Python 2中返回一个字符串.
如果您正在使用six编写2/3兼容代码,则six.input()可以raw_input()在Python 2和input()Python 3中找到它们.
更新:此方法仅在您将来安装并且上面的答案更好且更通用时才有效.
从这个备忘单中有另一种看起来更干净的方法:
# Python 2 and 3:
from builtins import input
Run Code Online (Sandbox Code Playgroud)
| 归档时间: |
|
| 查看次数: |
19497 次 |
| 最近记录: |