Check if string contains list of characters python

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

To learn other useful string methods in Python, feel free to check this article.

Below you find a more detailed guide of how to check if a string contains characters from a list.

Step-by-step Guide

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

The esmre library does the trick. In your case, the simpler, esm (part of esmre) is what you want.

https://pypi.python.org/pypi/esmre/

https://code.google.com/p/esmre/

They have good documentation and examples: Taken from their examples:

>>> import esm
>>> index = esm.Index()
>>> index.enter("he")
>>> index.enter("she")
>>> index.enter("his")
>>> index.enter("hers")
>>> index.fix()
>>> index.query("this here is history")
[((1, 4), 'his'), ((5, 7), 'he'), ((13, 16), 'his')]
>>> index.query("Those are his sheep!")
[((10, 13), 'his'), ((14, 17), 'she'), ((15, 17), 'he')]
>>> 

I ran some performance tests:

import random, timeit, string, esm

def uz(lelist, lestring):
    for x in lelist:
        if lestring.count(x):
            return 'Yep. "%s" contains characters from "%s" item.' % (lestring, x)



def ab(lelist, lestring):
    return [e for e in lelist if e in lestring]


def use_esm(index, lestring):
    return index.query(lestring)

for TEXT_LEN in [5, 50, 1000]:
    for SEARCH_LEN in [5, 20]:
        for N in [5, 50, 1000, 10000]:
            if TEXT_LEN < SEARCH_LEN:
                continue

            print 'TEXT_LEN:', TEXT_LEN, 'SEARCH_LEN:', SEARCH_LEN, 'N:', N

            lestring = ''.join((random.choice(string.ascii_uppercase + string.digits) for _ in range(TEXT_LEN)))
            lelist = [''.join((random.choice(string.ascii_uppercase + string.digits) for _ in range(SEARCH_LEN))) for _
                      in range(N)]

            index = esm.Index()
            for i in lelist:
                index.enter(i)
            index.fix()

            t_ab = timeit.Timer("ab(lelist, lestring)", setup="from __main__ import lelist, lestring, ab")
            t_uz = timeit.Timer("uz(lelist, lestring)", setup="from __main__ import lelist, lestring, uz")
            t_esm = timeit.Timer("use_esm(index, lestring)", setup="from __main__ import index, lestring, use_esm")

            ab_time = t_ab.timeit(1000)
            uz_time = t_uz.timeit(1000)
            esm_time = t_esm.timeit(1000)

            min_time = min(ab_time, uz_time, esm_time)
            print '  ab%s: %f' % ('*' if ab_time == min_time else '', ab_time)
            print '  uz%s: %f' % ('*' if uz_time == min_time else '', uz_time)
            print '  esm%s %f:' % ('*' if esm_time == min_time else '', esm_time)

And got that results depends mostly on the number of items that one is looking for (in my case, 'N'):

TEXT_LEN: 1000 SEARCH_LEN: 20 N: 5
  ab*: 0.001733
  uz: 0.002512
  esm 0.126853:

TEXT_LEN: 1000 SEARCH_LEN: 20 N: 50
  ab*: 0.017564
  uz: 0.023701
  esm 0.079925:

TEXT_LEN: 1000 SEARCH_LEN: 20 N: 1000
  ab: 0.370371
  uz: 0.489523
  esm* 0.133783:

TEXT_LEN: 1000 SEARCH_LEN: 20 N: 10000
  ab: 3.678790
  uz: 4.883575
  esm* 0.259605:

How do you check if a string contains a list of strings?

Using String. contains() method for each substring. You can terminate the loop on the first match of the substring, or create a utility function that returns true if the specified string contains any of the substrings from the specified list.

How do you check if a character is present in a list in Python?

We can use the in-built python List method, count(), to check if the passed element exists in the List. If the passed element exists in the List, the count() method will show the number of times it occurs in the entire list. If it is a non-zero positive number, it means an element exists in the List.

How do you check if a string contains a character?

Use the String. includes() method to check if a string contains a character, e.g. if (str. includes(char)) {} . The include() method will return true if the string contains the provided character, otherwise false is returned.

How do you check if a string contains a certain word in Python?

The simplest way to check if a string contains a substring in Python is to use the in operator. This will return True or False depending on whether the substring is found. For example: sentence = 'There are more trees on Earth than stars in the Milky Way galaxy' word = 'galaxy' if word in sentence: print('Word found.