Python 2.7 获取用户输入并作为不带引号的字符串进行操作

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/4960208/
Warning: these are provided under cc-by-sa 4.0 license. You are free to use/share it, But you must attribute it to the original authors (not me): StackOverFlow

提示:将鼠标放在中文语句上可以显示对应的英文。显示中英文
时间:2020-08-18 18:20:50  来源:igfitidea点击:

Python 2.7 getting user input and manipulating as string without quotations

pythonstringpython-2.7

提问by Mike Lee

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

有没有办法让 testVar 成为一个字符串,而无需让用户在引号中输入他的响应?即“你好”与你好

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

如果用户输入 Hello,我会收到以下错误:

NameError: name 'Hello' is not defined

NameError:未定义名称“Hello”

采纳答案by Sven Marnach

Use raw_input()instead of input():

使用raw_input()代替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.

input()实际上将输入评估为 Python 代码。我建议永远不要使用它。 raw_input()返回用户输入的逐字字符串。

回答by chuck

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

该函数input还将评估它刚刚读取为 python 代码的数据,这并不是您真正想要的。

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

通用方法是将用户输入(来自sys.stdin)视为任何其他文件。尝试

import sys
sys.stdin.readline()

If you want to keep it short, you can use raw_inputwhich is the same as inputbut omits the evaluation.

如果你想保持简短,你可以使用raw_inputwhich 与input但省略评估相同。

回答by Artur Gaspar

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

回答by Sanjay Ursal

The issue seems to be resolved in Python version 3.4.2.

该问题似乎在 Python 3.4.2 版中得到解决。

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

Will work fine.

会工作得很好。

回答by Prav001

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

如果你想在 python 2.x 中使用 input 而不是 raw_input,那么这个技巧会派上用场

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

After which,

之后,

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

will work just fine.

会工作得很好。

回答by st_443

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

回答by Mak

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

如果我将来需要转移到 python 3,这是我的工作,以确保安全。

def _input(msg):
  return raw_input(msg)

回答by Projesh Bhoumik

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.

我们可以使用raw_input()Python 2 中的input()函数和 Python 3 中的函数。默认情况下,输入函数接受字符串格式的输入。对于其他数据类型,您必须转换用户输入。

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

在 Python 2 中,我们使用该raw_input()函数。它等待用户输入一些输入并按下return,我们需要通过转换为我们想要的数据类型来将值存储在变量中。使用类型转换时要小心

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.

在 Python 3 中,我们使用 input() 函数返回用户输入值。

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

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

如果您输入一个字符串、int、float、eval,它将作为字符串输入

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

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

如果为 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

如果您输入一个字符串进行浮点转换 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 definedThose error also applicable for Python 2.

如果为 eval cast 输入字符串,则NameError: name ' ' is not defined这些错误也适用于 Python 2。