Python How to Check If String Contains Characters from a List

String contains characters from a list

To check if a Python string contains all the characters from a list, check if each character exists in the word:

Here is an example:

chars = ["H", "e", "y"]
word = "Hello"

has_all = all([char in word for char in chars])

print(has_all)

Output:

False

This is the quick answer. Below you find a more detailed description of how to solve the problem.

Step-by-step Solution

Given a list of characters and a string, you can check if all the characters of a list are found in the target string following these steps:

  1. Loop through the list of characters.
  2. Check if a character is in the target string.
  3. Add the truth to a list.
  4. Check if all truth values in a list are True.

Here is how it looks in code:

chars = ["H", "e", "y"]
word = "Hello"
          
truths = []
          
# 1. Loop through the chars
for char in chars:
    # 2. Check if a character is in the target string
    truth = char in word
    # 3. Add the truth to a truths list
    truths.append(truth)
          
# 4. Check if all boolean values are True
has_all = True
for truth in truths:
    has_all = has_all and truth
          
print(has_all)

Output:

False

But you can make this piece of code shorter by using:

  • List comprehension to shorten the 1st for loop.
  • Built-in all() method to get rid of the 2nd loop. This method checks if all booleans are True.

This makes the code look the same as in the example solution in the introduction:

chars = ["H", "e", "y"]
word = "Hello"
          
has_all = all([char in word for char in chars])
          
print(has_all)

Output:

False

To be more general, you can implement a function that gets the job done.

Here is how it looks in code:

def has_all(chars, string):
    return all([char in string for char in chars])
          
# Example call
print(has_all("Hello", ["H","i"]))

Output:

False

Conclusion

Today you learned how to check if a Python string contains all characters present in a list.

To recap, you need to run a loop through the list of the characters. Then you need to check if each of those characters exists in the target string.

Thanks for reading.

Happy coding!

Further Reading

50 Python Interview Questions

Share on facebook
Share on twitter
Share on linkedin

Leave a Comment

Your email address will not be published.