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.
How to check if a string contains only certain characters?
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 –
- Create a set (or a string) containing the allowed characters.
- 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. - Use the Python built-in
all()
function to returnTrue
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.
Highlighted programs for you
Flatiron School
Flatiron School
University of Maryland Global Campus
University of Maryland Global Campus
Creighton University
Creighton University
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 –
- Python – Check If String Contains Only Letters
- Python – Check if a String Contains Numbers
- Check if a String contains a Substring in Python
Subscribe to our newsletter for more informative guides and tutorials.
We do not spam and you can opt out any time.