Check if string contains only certain characters

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.

📚 Data Science Programs By Skill Level

Introductory

Intermediate ⭐⭐⭐

Advanced ⭐⭐⭐⭐⭐

🔎 Find Data Science Programs 👨‍💻 111,889 already enrolled

Disclaimer: Data Science Parichay is reader supported. When you purchase a course through a link on this site, we may earn a small commission at no additional cost to you. Earned commissions help support this website and its team of writers.

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 Raj

    Piyush is a data professional passionate about using data to understand things better and make informed decisions. He has experience working as a Data Scientist in the consulting domain and holds an engineering degree from IIT Roorkee. His hobbies include watching cricket, reading, and working on side projects.

Scroll to Top