Check If String Contains Only Certain Characters In Python

Check If String Contains Only Certain Characters In Python | Here, this article will discuss how to check if a string contains only certain characters using Python programming language.

To check if a string contains only certain characters, we can use the following method:-

  • Using Regular Expressions
  • Using Character List

Check If String Contains Only Certain Characters In Python Using Regular Expressions

Regular expressions are used to perform some operation for every element or select a subset of elements that meet a condition. We will use the re.match() method of the regular expressions library. 

In the pattern, if there are any other characters in the string, then False is returned, else True is returned.

import re
string = "abcdabcdabcd"
print("The given string is:", string)

print("Check if the given string contains only specific characters: ")
print(bool(re.match('^[abcd]+$', string)))

Output:-

The given string is: abcdabcdabcd
Check if the given string contains only specific characters:
True

Check If String Contains Only Certain Characters In Python Using Character List

We can make a list of wanted characters and we will check if the characters present in the string belong to this list or not. If all the characters are not belonging to the character list, then False is returned, else True is returned.

acceptable_chars = ['a', 'b', 'c', 'd']
str1 = "abcabcdabcd"

print("The given string is:", str1)

validation = [i in acceptable_chars for i in str1]
print("Check if the given string contains only specific characters:")
print(all(validation))

Output:-

The given string is: abcabcdabcd
Check if the given string contains only specific characters:
True

So, in the following article, we have learned how to check if String contains only certain Characters in Python programming language. Hope you all enjoyed the post find it useful.

If you enjoyed this post, share it with your friends. Do you want to share more information about the topic discussed above or do you find anything incorrect? Let us know in the comments. Thank you!

Leave a Comment

Your email address will not be published. Required fields are marked *