Skip to Content

Check If String Contains Only Certain Characters in Python

In this tutorial, we will look at how to check if a string contains only certain characters in Python with the help of some examples.

You can use a combination of the all() function and the membership operator, in to check if a string contains only certain characters in Python. Use the following steps –

  1. Create a set (or a string) containing the allowed characters.
  2. Iterate through the characters in the string and use the membership operator "in" to check if the character is in the allowed set of characters.
  3. Use the Python built-in all() function to return True only if all the characters in the string are present in the allowed characters.

Let’s look at an example.

# string
s = "ababaaaab"
# string with only allowed characters
allowed_s = "ab"
# check if s contains only allowed characters
print(all(ch in allowed_s for ch in s))

Output:

True

Here, we get True as the output because all the characters in the string s are present in the allowed characters.

Let’s look at another example.

# string
s = "abcbaaaab"
# string with only allowed characters
allowed_s = "ab"
# check if s contains only allowed characters
print(all(ch in allowed_s for ch in s))

Output:

False

Here, we get False as the output because the character “c” is not in the allowed characters.

We can modify the allowed characters string to suit our specific use case. For example, if you want to check if the string contains only digits you can use “0123456789” as your allowed characters string.

# string
s = "1150"
# string with only allowed characters
allowed_s = "0123456789"
# check if s contains only allowed characters
print(all(ch in allowed_s for ch in s))

Output:

True

Note that for the above use case, you can also just directly use the string isdigit() function.

You might also be interested in –


Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.


Author

  • Piyush is a data scientist passionate about using data to understand things better and make informed decisions. In the past, he's worked as a Data Scientist for ZS and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.