-2

I have a list:

my_list = ['hello', 'def-456', 'ghello', 'abc', 'helloajisjioj']

and want to search for items that contain the string 'hello'. How can I do that?

The result should be: 'hello', 'ghello', 'helloajisjioj'

How can i do that? I tried the find, but he only find 'hello'.

i tried something like:

if 'hello' in my_list:

Thanks for your answers.

Psytho
  • 3,313
  • 2
  • 19
  • 27
guiguilecodeur
  • 429
  • 2
  • 15
  • 2
    This is literally the same question as [Check if a Python list item contains a string inside another string](https://stackoverflow.com/questions/4843158/check-if-a-python-list-item-contains-a-string-inside-another-string), including some examples and the failed attempt. – mkrieger1 Jun 28 '21 at 12:19

3 Answers3

2

Here is a one liner

print([x for x in my_list if "hello" in x])

Output:

['hello', 'ghello', 'helloajisjioj']
  • Thank you, it fuctions, but i don't understand de x for x in my_list? is it a double for loop? – guiguilecodeur Jun 28 '21 at 12:21
  • 1
    That is list comprehension. it means: ```a=[]```, ```for x in my_list:```, ```if hello in x: ```, ```a.append(x)```, ```print(a)``` @guiguilecodeur –  Jun 28 '21 at 12:23
  • It's simpler to point to the documentation: https://docs.python.org/3/tutorial/datastructures.html#list-comprehensions. – VisioN Jun 28 '21 at 12:24
1

There are many ways to do this, but the nices is probably with list comprehension:

words_with_hello = [word for word in my_list if "hello" in word]
tituszban
  • 4,797
  • 2
  • 19
  • 30
1

We can also use filter

>>> list(filter(lambda x: 'hello' in x, my_list))
['hello', 'ghello', 'helloajisjioj']
crayxt
  • 2,367
  • 2
  • 12
  • 17