How to Only Accept a Single Character from User Input in Python?

Estimated read time 2 min read

In Python, you can use the built-in input() function to accept user input. To only accept a single character from user input, you can use the input() function inside a loop that checks the length of the input string.

Here is an example:

while True:
    user_input = input("Enter a single character: ")
    if len(user_input) == 1:
        print("Error: Please enter a single character.")

print("You entered:", user_input)

In this example, we use a while loop to repeatedly prompt the user to enter a single character. We use the input() function to accept user input and store it in the user_input variable.

We check the length of the user_input string using the len() function. If the length is 1, we break out of the loop and print the input using the print() function. If the length is greater than 1, we print an error message and continue the loop.

Note that this example only works if the user enters a single Unicode character. If the user enters a multi-byte character, such as an emoji or a non-ASCII character, the length of the input string may be greater than 1. In this case, you may need to use a different method to validate the input.

You May Also Like

More From Author

+ There are no comments

Add yours

Leave a Reply