-1
S = ['cat','tor','tutorial','item','aba','tori']  
T = "oti"


for item in S:
    for i in item:
        if i in T:
            print(item)

I want to get 'tori' and 'tutorial' because those are the 2 words that contain o, t, i. The code above will print everything from the list. Using find() is not an option because there is no match.

Will using match be a good option here? I could use some hint here. Thanks in advance.

Josh21
  • 506
  • 5
  • 15
Sheikh Rahman
  • 895
  • 3
  • 14
  • 29

1 Answers1

1

Use sets for membership testing.

>>> 
>>> T = 'oti'
>>> S = ['cat','tor','tutorial','item','aba','tori']
>>> t = set(T)
>>> t
{'o', 't', 'i'}
>>> for thing in S:
...     if t.issubset(thing):
            print(thing)


tutorial
tori
>>> 

This won't work if there are duplicate characters.

>>> q = set('otti')
>>> for thing in S:
...     if q.issubset(thing):
            print(thing)


tutorial
tori
>>>

Using all

>>> 
>>> for thing in S:
...     if all(c in thing for c in T):
            print(thing)


tutorial
tori
>>> 
wwii
  • 23,232
  • 7
  • 37
  • 77