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() 
0

3 Answers 3

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() 
Sign up to request clarification or add additional context in comments.

1 Comment

If you want this to work without pressing enter, one simple solution is to use sshkeyboard. It requires less coding, and it is a cross platform solution.
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.

Comments

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.

1 Comment

smart trick Matt :)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.