Python 2.7 getting user input and manipulating as

2018-12-31 19:26发布

问题:

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

回答1:

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:

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.



回答3:

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.



回答4:

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.



回答5:

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


回答6:

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!\")


回答7:

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)


回答8:

The issue seems to be resolved in Python version 3.4.2.

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

Will work fine.



标签: python string