如何在python 2.7中将用户输入转换为字符串

声明:本页面是StackOverFlow热门问题的中英对照翻译,遵循CC BY-SA 4.0协议,如果您需要使用它,必须同样遵循CC BY-SA许可,注明原文地址和作者信息,同时你必须将它归于原作者(不是我):StackOverFlow 原文地址: http://stackoverflow.com/questions/36787345/
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-19 18:21:16  来源:igfitidea点击:

How to convert user input to string in python 2.7

pythonstringpython-2.7user-inputnameerror

提问by sarang.g

When I enter

当我进入

username = str(input("Username:"))

username = str(input("Username:"))

password = str(input("Password:"))

password = str(input("Password:"))

and after running the program, I fill in the input with my name and hit enter

运行程序后,我用我的名字填写输入并按回车

username = sarang

username = sarang

I get the error

我收到错误

NameError: name 'sarang' is not defined

NameError: name 'sarang' is not defined

I have tried

我试过了

username = '"{}"'.format(input("Username:"))

username = '"{}"'.format(input("Username:"))

and

password = '"{}"'.format(input("Password:"))

password = '"{}"'.format(input("Password:"))

but I end up getting the same error.

但我最终得到了同样的错误。

How do I convert the input into a string and fix the error?

如何将输入转换为字符串并修复错误?

回答by jDo

Use raw_input()in Python 2.x and input()in Python 3.x to get a string.

使用raw_input()在Python 2.x和input()Python中3.X得到一个字符串。

You have two choices: run your code via Python 3.x or change input()to raw_input()in your code.

您有两种选择:通过 Python 3.x 运行您的代码或在您的代码中更改input()raw_input()

Python 2.x input()evaluates the user input as code, not as data. It looks for a variable in your existing code called sarangbut fails to find it; thus a NameErroris thrown.

Python 2.xinput()将用户输入评估为代码,而不是数据。它会在您调用的现有代码中查找变量,sarang但找不到;因此 aNameError被抛出。

Side note: you could add this to your code and call input_func()instead. It will pick the right input method automatically so your code will work the same in Python 2.x and 3.x:

旁注:您可以将其添加到您的代码中并input_func()改为调用。它将自动选择正确的输入法,因此您的代码在 Python 2.x 和 3.x 中的工作方式相同:

input_func = None
try:
    input_func = raw_input
except NameError:
    input_func = input

# test it

username = input_func("Username:")
print(username)

Check out this questionfor more details.

查看此问题了解更多详情。

回答by Rochak Bhalla

You have to explicitly use raw_input(prompt), instead of just using input(prompt). As you are currently using Python 2.x which supports this type of formatting for receiving an input from user.

您必须显式使用 raw_input(prompt),而不仅仅是使用 input(prompt)。由于您目前使用的是 Python 2.x,它支持这种格式以接收用户输入。

回答by Akash Kandpal

In Python 2, raw_input()returns a string, and input()tries to run the input as a Python expression.

在 Python 2 中,raw_input()返回一个字符串,并input()尝试将输入作为 Python 表达式运行。

Since getting a string was almost always what you wanted, Python 3 does that with input().

由于获取字符串几乎总是您想要的,因此 Python 3 使用input().