How to convert user input to string in python 2.7

36,313

Use raw_input() in Python 2.x and input() in Python 3.x to get a string.

You have two choices: run your code via Python 3.x or change input() to raw_input() in your code.

Python 2.x input() evaluates the user input as code, not as data. It looks for a variable in your existing code called sarang but fails to find it; thus a NameError is thrown.

Side note: you could add this to your code and call input_func() instead. It will pick the right input method automatically so your code will work the same in Python 2.x and 3.x:

input_func = None
try:
    input_func = raw_input
except NameError:
    input_func = input

# test it

username = input_func("Username:")
print(username)

Check out this question for more details.

Share:
36,313
sarang.g
Author by

sarang.g

Updated on January 03, 2020

Comments

  • sarang.g
    sarang.g over 4 years

    When I enter

    username = str(input("Username:"))

    password = str(input("Password:"))

    and after running the program, I fill in the input with my name and hit enter

    username = sarang

    I get the error

    NameError: name 'sarang' is not defined

    I have tried

    username = '"{}"'.format(input("Username:"))

    and

    password = '"{}"'.format(input("Password:"))

    but I end up getting the same error.

    How do I convert the input into a string and fix the error?

  • sarang.g
    sarang.g about 8 years
    the problem is fixed thanks to your help
  • jDo
    jDo about 8 years
    @sarang.g Nice, you’re welcome!