How to convert user input to string in python 2.7

sarang.g picture sarang.g · Apr 22, 2016 · Viewed 32k times · Source

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?

Answer

jDo picture jDo · Apr 22, 2016

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.