Only accept a single character from user Input in Python

avatar
Borislav Hadzhiev

Last updated: Apr 9, 2024
5 min

banner

# Table of Contents

  1. Only accept a single character from user Input in Python
  2. Only Letters when taking user Input in Python

# Only accept a single character from user Input in Python

To only accept a single character from user input:

  1. Use a while loop to iterate until the user enters a single character.
  2. If the user enters a single character, use the break statement to break out of the loop.
  3. If the condition is not met, prompt the user again.
main.py
user_input = '' while True: user_input = input('Enter a single character: ') if len(user_input) == 1: print(user_input) break else: print('Enter a single character to continue.') continue # ๐Ÿ‘‡๏ธ if you need to convert the character to lower or uppercase print(user_input.lower()) print(user_input.upper())

input only accept one character

The code for this article is available on GitHub

We used a while loop to iterate until the user enters a single character.

The if statement uses the len() function to check if the user entered a single character.

The len() function returns the length (the number of items) of an object.

main.py
print(len('a')) # ๐Ÿ‘‰๏ธ 1 print(len('ab')) # ๐Ÿ‘‰๏ธ 2
The argument the function takes may be a sequence (a string, tuple, list, range or bytes) or a collection (a dictionary, set, or frozen set).

If the user entered a single character, we use the break statement to exit out of the loop.

main.py
user_input = '' while True: user_input = input('Enter a single character: ') if len(user_input) == 1: print(user_input) break else: print('Enter a single character to continue.') continue

The break statement breaks out of the innermost enclosing for or while loop.

If the user enters zero or more than 1 character, we prompt them again.

The continue statement continues with the next iteration of the loop.

When validating user input in a while loop, we use the continue statement when the input is invalid.

If the input is valid, we use the break statement to exit out of the while loop.

# Only accept a single Letter from user Input

Use the str.isalpha() method if you only want to allow the user to enter a single letter.

main.py
user_input = '' while True: user_input = input('Enter a single letter: ') if len(user_input) == 1 and user_input.isalpha(): print(user_input) break else: print('Enter a single letter to continue.') continue

input only accept one letter

The code for this article is available on GitHub

We used the boolean AND operator, so for the if block to run, both conditions have to be met.

The str.isalpha() method returns True if all characters in the string are alphabetic and there is at least one character, otherwise False is returned.

main.py
print('a'.isalpha()) # ๐Ÿ‘‰๏ธ True print('1'.isalpha()) # ๐Ÿ‘‰๏ธ False

If the user enters a single letter, the if block runs and we exit out of the while loop, otherwise, we prompt the user again.

# Only allow letters when taking user Input in Python

To only allow letters when taking user input:

  1. Use a while loop to iterate until the user enters only letters.
  2. Use the str.isalpha() method to check if the user entered only letters.
  3. If the condition is met, break out of the loop.
main.py
user_input = '' while True: user_input = input('Enter letters only: ') if not user_input.isalpha(): print('Enter only letters') continue else: print(user_input) break

only allow letters when taking user input

The code for this article is available on GitHub

We used a while loop to iterate until the user enters only letters.

On each iteration, we check if the user didn't enter only letters and use a continue statement if the condition is met.

The continue statement continues with the next iteration of the loop.

The str.isalpha() method returns True if all characters in the string are alphabetic and there is at least one character, otherwise False is returned.

main.py
print('avocado'.isalpha()) # ๐Ÿ‘‰๏ธ True # ๐Ÿ‘‡๏ธ contains space print('one two'.isalpha()) # ๐Ÿ‘‰๏ธ False
If you also want to allow spaces, scroll down to the last code snippet.

If the user entered only letters, we print the input value and break out of the loop.

The break statement breaks out of the innermost enclosing for or while loop.

The input function takes an optional prompt argument and writes it to standard output without a trailing newline.

# Only allow letters when taking user Input using regex

Alternatively, you can use a regular expression.

main.py
import re user_input = '' while True: user_input = input('Enter letters only: ') if not re.match(r'^[a-zA-Z]+$', user_input): print('Enter only letters') continue else: print(user_input) break
The code for this article is available on GitHub

The code snippet achieves the same result but uses a regular expression to validate the user input.

# Only allowing letters and spaces when taking user input

If you also want to allow spaces, use the following regular expression instead.

main.py
import re user_input = '' while True: user_input = input('Enter letters only: ') # ๐Ÿ‘‡๏ธ also allows spaces if not re.match(r'^[a-zA-Z\s]+$', user_input): print('Enter only letters') continue else: print(user_input) break

The re.match() method returns a match object if the provided regular expression is matched in the string.

The match method returns None if the string does not match the regex pattern.

The first argument we passed to the re.match method is a regular expression.

The square brackets [] are used to indicate a set of characters.

The a-z and A-Z characters represent lowercase and uppercase ranges of letters.

The caret ^ matches the start of the string and the dollar sign $ matches the end of the string.

The plus + causes the regular expression to match 1 or more repetitions of the preceding character (the letter ranges).

main.py
import re user_input = '' while True: user_input = input('Enter letters only: ') # ๐Ÿ‘‡๏ธ also allows spaces if not re.match(r'^[a-zA-Z\s]+$', user_input): print('Enter only letters') continue else: print(user_input) break
The code for this article is available on GitHub

The \s character matches Unicode whitespace characters like [ \t\n\r\f\v].

If the user didn't enter only letters, we use the continue statement to prompt them for input again.

Otherwise, we use the break statement to break out of the while loop.

If you ever need help reading or writing a regular expression, consult the regular expression syntax subheading in the official docs.

The page contains a list of all of the special characters with many useful examples.

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev