Python 2.7 getting user input and manipulating as string without quotations

PythonStringPython 2.7

Python Problem Overview


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

Python Solutions


Solution 1 - Python

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.

Solution 2 - Python

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
sys.stdin.readline()

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

Solution 3 - Python

We can use the raw_input() function in Python 2 and the input() function in Python 3. By default the input function takes an input in string format. For other data type you have to cast the user input.

In Python 2 we use the raw_input() function. It waits for the user to type some input and press return and we need to store the value in a variable by casting as our desire data type. Be careful when using type casting

x = raw_input("Enter a number: ") #String input

x = int(raw_input("Enter a number: ")) #integer input

x = float(raw_input("Enter a float number: ")) #float input

x = eval(raw_input("Enter a float number: ")) #eval input

In Python 3 we use the input() function which returns a user input value.

x = input("Enter a number: ") #String input

If you enter a string, int, float, eval it will take as string input

x = int(input("Enter a number: ")) #integer input

If you enter a string for int cast ValueError: invalid literal for int() with base 10:

x = float(input("Enter a float number: ")) #float input

If you enter a string for float cast ValueError: could not convert string to float

x = eval(input("Enter a float number: ")) #eval input

If you enter a string for eval cast NameError: name ' ' is not defined Those error also applicable for Python 2.

Solution 4 - Python

If you want to use input instead of raw_input in python 2.x,then this trick will come handy

    if hasattr(__builtins__, 'raw_input'):
      input=raw_input

After which,

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

will work just fine.

Solution 5 - Python

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

Solution 6 - Python

My Working code with fixes:

import random
import math
print "Welcome to Sam's Math Test"
num1= random.randint(1, 10)
num2= random.randint(1, 10)
num3= random.randint(1, 10)
list=[num1, num2, num3]
maxNum= max(list)
minNum= min(list)
sqrtOne= math.sqrt(num1)

correct= False
while(correct == False):
    guess1= input("Which number is the highest? "+ str(list) + ": ")
    if maxNum == guess1:
	    print("Correct!")
	    correct = True
    else:
	    print("Incorrect, try again")

correct= False
while(correct == False):
guess2= input("Which number is the lowest? " + str(list) +": ")
if minNum == guess2:
	 print("Correct!")
	 correct = True
else:
	print("Incorrect, try again")

correct= False
while(correct == False):
    guess3= raw_input("Is the square root of " + str(num1) + " greater than or equal to 2? (y/n): ")
    if sqrtOne >= 2.0 and str(guess3) == "y":
	    print("Correct!")
	    correct = True
    elif sqrtOne < 2.0 and str(guess3) == "n":
	    print("Correct!")
	    correct = True
    else:
	    print("Incorrect, try again")

print("Thanks for playing!")

Solution 7 - Python

This is my work around to fail safe in case if i will need to move to python 3 in future.

def _input(msg):
  return raw_input(msg)

Solution 8 - Python

The issue seems to be resolved in Python version 3.4.2.

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

Will work fine.

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionMike LeeView Question on Stackoverflow
Solution 1 - PythonSven MarnachView Answer on Stackoverflow
Solution 2 - PythonchuckView Answer on Stackoverflow
Solution 3 - PythonProjesh BhoumikView Answer on Stackoverflow
Solution 4 - PythonPrav001View Answer on Stackoverflow
Solution 5 - PythonArtur GasparView Answer on Stackoverflow
Solution 6 - Pythonst_443View Answer on Stackoverflow
Solution 7 - PythonMakView Answer on Stackoverflow
Solution 8 - PythonSanjay UrsalView Answer on Stackoverflow