Python 2.7获取用户输入并以字符串形式操作而不带引号

Mik*_*Lee 142 python string python-2.7

我想从用户那里获取一个字符串,然后操纵它.

testVar = input("Ask user for something.")
Run Code Online (Sandbox Code Playgroud)

有没有一种方法让testVar成为一个字符串而没有我让用户在引号中键入他的响应?即"你好"与你好

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

NameError:未定义名称"Hello"

Sve*_*ach 259

使用raw_input()而不是input():

testVar = raw_input("Ask user for something.")
Run Code Online (Sandbox Code Playgroud)

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

  • 虽然对于使用Python**3**阅读此内容的人来说,`input`现在可以这样工作,但raw_input已经消失了. (104认同)
  • 您希望用户将python代码插入到您自己的代码中的情况如何? (3认同)

chu*_*uck 11

该函数input还将评估它刚刚读取的数据作为python代码,这实际上并不是你想要的.

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

import sys
sys.stdin.readline()
Run Code Online (Sandbox Code Playgroud)

如果你想保持简短,你可以使用与评估raw_input相同input但忽略的评估.

  • 此外,如果您正在编写一个交互式程序,请考虑导入`readline` - 这将提供类似于bash的功能(历史记录开箱即用,自动完成将需要一些腿部工作) (2认同)

Pro*_*mik 11

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

在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
Run Code Online (Sandbox Code Playgroud)

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

x = input("Enter a number: ") #String input
Run Code Online (Sandbox Code Playgroud)

如果输入字符串,int,float,eval,它将作为字符串输入

x = int(input("Enter a number: ")) #integer input
Run Code Online (Sandbox Code Playgroud)

如果为int cast输入字符串 ValueError: invalid literal for int() with base 10:

x = float(input("Enter a float number: ")) #float input
Run Code Online (Sandbox Code Playgroud)

如果为float cast输入字符串 ValueError: could not convert string to float

x = eval(input("Enter a float number: ")) #eval input
Run Code Online (Sandbox Code Playgroud)

如果输入eval的字符串,那么NameError: name ' ' is not defined 这些错误也适用于Python 2.


Pra*_*001 5

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

    if hasattr(__builtins__, 'raw_input'):
      input=raw_input
Run Code Online (Sandbox Code Playgroud)

之后,

testVar = input("Ask user for something.")
Run Code Online (Sandbox Code Playgroud)

会工作得很好.