Check if String contains only certain Characters in Python

avatar

Borislav Hadzhiev

Last updated: Sep 19, 2022

banner

Photo from Unsplash

Check if String contains only certain Characters in Python #

To check if a string contains only certain characters:

  1. Use a generator expression to iterate over the string.
  2. Check if each character is contained in the set of characters.
  3. If the condition is met for all characters, the string only contains the specified characters.
main.py
def contains_certain_characters(string, characters): return all(char in characters for char in string) # 👇️ True print(contains_certain_characters('bh123', 'bh12345678')) # 👇️ False print(contains_certain_characters('bobby', 'abcd12345')) if contains_certain_characters('asd', 'asdfg123'): # 👇️ this runs print('The string contains only the specified characters') else: print('The string does NOT contain only the specified characters')
If you're looking for a more flexible regex solution, scroll down to the next subheading.

We used a generator expression to iterate over the string.

Generator expressions are used to perform some operation for every element or select a subset of elements that meet a condition.

On each iteration, we check if the current character is contained in the set of characters and return the result.

The in operator tests for membership. For example, x in s evaluates to True if x is a member of s, otherwise it evaluates to False.

The all() built-in function takes an iterable as an argument and returns True if all elements in the iterable are truthy (or the iterable is empty).

main.py
characters = 'abcd12345' result = all(char in characters for char in 'ab12') print(result) # 👉️ True result = all(char in characters for char in 'zx12') print(result) # 👉️ False

If any of the characters from the string is not contained in the set of characters, the all() function short-circuits and returns False.

Note that the all() function returns True for any condition if the iterable is empty.
main.py
characters = 'abcd12345' my_str = '' result = all(char in characters for char in my_str) print(result) # 👉️ True

If you need to return False if the string is empty, check for the string's length.

main.py
characters = 'abcd12345' my_str = '' result = (len(my_str) > 0 and all(char in characters for char in my_str)) print(result) # 👉️ False

Alternatively, you can use the re.match() method.

Check if String contains only certain Characters using re.match() #

Use the re.match() method to check if a string contains only certain characters. The re.match method will return a match object if the string only contains the specified characters, otherwise None is returned.

main.py
import re result = bool(re.match(r'^[abc123 _-]+$', 'a-b _12')) print(result) # 👉️ True result = bool(re.match(r'^[abc123 _-]+$', 'a@b')) print(result) # 👉️ False

The re.match method returns a match object if the provided regular expression is matched in the string.

The match method returns None if the string doesn't match the regex pattern.

The first argument we passed to the re.match method is a regular expression.

The square brackets [] are used to indicate a set of characters.

The caret ^ matches the start of the string and the dollar sign $ matches the end of the string.

The plus + causes the regular expression to match 1 or more repetitions of the preceding character (the characters between the square brackets).

We used the bool() class to convert the result to a boolean.

The regular expression in the example matches a string that starts with and contains any of the specified characters between the square brackets:

  • the letters a, b, c
  • the numbers 1, 2, 3
  • spaces
  • underscores
  • hyphens
main.py
import re result = bool(re.match(r'^[abc123 _-]+$', 'a-b _12')) print(result) # 👉️ True result = bool(re.match(r'^[abc123 _-]+$', 'a@b')) print(result) # 👉️ False

You can tweak the regex according to your needs by updating the set of characters between the square brackets.

If you ever need help reading or writing a regular expression, consult the regular expression syntax subheading in the official docs.

The page contains a list of all of the special characters with many useful examples.

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.