How To Only Allow String Input In Python

In this tutorial, we will learn how to restrict user input to only accept string values in Python. This is important because sometimes we need to make sure that user input is only valid if it is formatted as a string.

We will create a simple function that checks the user input and prompts the user to enter the correct input if it’s not a string.

Step 1: Accept user input

To receive input from the user in Python, we can use the built-in function input(). The input() function waits for the user to enter some text from the keyboard and returns the entered text as a string. Here’s an example:

However, by default, the input() function accepts any input, including numbers and special characters. We need to restrict it to accept only strings.

Step 2: Create a function to validate string input

We will create a custom function named is_string() that accepts user input as its parameter and checks if it is a string. If the input is a string, the function returns True, otherwise it returns False.

The function uses the isinstance() method to check if the given input is an instance of the str class. It also uses the isalpha() method to ensure that the input only contains alphabetical characters (i.e., no numbers, white spaces, or special characters).

Step 3: Re-prompt user for input until it’s a string

We will use a while loop that keeps prompting the user for input until they provide a valid string. Inside the loop, we check if the input is a string using our custom is_string() function. If the input is a string, we break out of the loop; otherwise, we prompt the user to enter the correct input.

When the user enters a valid string, the loop exits, and we can continue with the rest of our program.

Full Code


Enter a string value: 123
Please enter a valid string.
Enter a string value: Hello
You entered: Hello

In conclusion, we’ve learned how to create a simple Python function to check for string input and how to re-prompt the user for input until they provide a valid string using a while loop. This method can be applied in cases where we want to ensure input validation for our Python programs.