Use of input/raw_input in python 2 and 3 [duplicate]

Bind raw_input to input in Python 2:

try:
    input = raw_input
except NameError:
    pass

Now input will return a string in Python 2 as well.


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.


I think the best way to do this is

import six

six.moves.input()

...it'll work across 2 and 3.


Update: This method only works if you have future installed and the answers above are much better and more generalizable.

From this cheatsheet there is another method that looks cleaner:

# Python 2 and 3:
from builtins import input