Python raw_input 应该只接受单个字符

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

raw_input should accept only single character

python

提问by MBanerjee

Possible Duplicate:
Python read a single character from the user

可能的重复:
Python 从用户读取单个字符

I am using below code.But instead of accepting a single character its allowing user to put more than a single character.

我正在使用下面的代码。但是它不接受单个字符,而是允许用户输入多个字符。

How can I fix that?

我该如何解决?

guess = raw_input(':')
guessInLower = guess.lower()

采纳答案by Matt

The following will continuously prompt the user for input until they enter exactly one character.

以下内容将不断提示用户输入,直到他们输入了一个字符。

userInput = ''
while len(userInput) != 1:
    userInput = raw_input(':')
guessInLower = userInput.lower()

This does the same, but also informs them of the one character limit before prompting again for input

这样做是一样的,但还会在再次提示输入之前通知他们一个字符的限制

while True:
    userInput = raw_input(':')
    if len(userInput) == 1:
        break
    print 'Please enter only one character'
guessInLower = userInput.lower()

It looks like you are expecting only letters. If that is the case you can expand this further to require that:

看起来你只期待字母。如果是这种情况,您可以进一步扩展以要求:

import string

while True:
    userInput = raw_input(':')
    if len(userInput) == 1:
        if userInput in string.letters:
            break
        print 'Please enter only letters'
    else:
        print 'Please enter only one character'
guessInLower = userInput.lower()

回答by pwaller

By default python uses line-buffered input, which means that the raw_input()call will not return until the user hits enter. If you want to turn off the line buffering, you may have to look at OS-specific things you can do. You can find a recipe demonstrating this here.

默认情况下,python 使用行缓冲输入,这意味着raw_input()在用户按下 Enter 之前调用不会返回。如果您想关闭行缓冲,您可能需要查看您可以执行的特定于操作系统的操作。您可以在此处找到演示此方法的食谱

回答by Matt

For Python 2.7.x,

对于 Python 2.7.x,

guess = raw_input(': ')[0].lower()

For Python 3.x

对于 Python 3.x

guess = input (': ')[0].lower()

in both cases, the first character from the terminal raw input string (no need for using '') will be lowered and passed by to the variable guess.

在这两种情况下,终端原始输入字符串中的第一个字符(不需要使用'')将被降低并传递给变量guess