Python 2.7 getting user input and manipulating as string without quotations


I want to get a string from a user, and then to manipulate it.

testVar = input("Ask user for something.")

Is there a way for testVar to be a string without me having the user type his response in quotes? i.e. "Hello" vs. Hello

If the user types in Hello, I get the following error:

NameError: name 'Hello' is not defined

12/26/2015 8:33:48 PM

Accepted Answer

Use raw_input() instead of input():

testVar = raw_input("Ask user for something.")

input() actually evaluates the input as Python code. I suggest to never use it. raw_input() returns the verbatim string entered by the user.

2/10/2011 5:01:33 PM

The function input will also evaluate the data it just read as python code, which is not really what you want.

The generic approach would be to treat the user input (from sys.stdin) like any other file. Try

import sys

If you want to keep it short, you can use raw_input which is the same as input but omits the evaluation.

Licensed under: CC-BY-SA with attribution
Not affiliated with: Stack Overflow