3

Possible Duplicate:
Python read a single character from the user

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()
Community
  • 1
  • 1
MBanerjee
  • 207
  • 1
  • 4
  • 10

3 Answers3

11

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()
Matt
  • 3,651
  • 3
  • 16
  • 35
  • If you want this to work without pressing enter, one simple solution is to use [sshkeyboard](https://sshkeyboard.readthedocs.io/en/latest/). It requires less coding, and it is a cross platform solution. – ilon Oct 28 '21 at 07:56
4

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.

pwaller
  • 601
  • 6
  • 10
3

For Python 2.7.x,

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

For 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.

helcode
  • 1,859
  • 1
  • 13
  • 32
Matt
  • 718
  • 6
  • 20