You can use the operator in
to check if a string is a substring from another.
It’s just not clear if you only want one of the strings in the list (the first one you find, for example), or if you want all that have the substring.
If you just want one of the strings, one way to do it is:
elemento_encontrado = None
busca = 'de bat'
lista = ['Jorge Henrique', 'Matheus Oliveira Santos', 'Sopa de batata doce', 'Algorítimos maravilhosos']
for s in lista:
if busca in s: # se "de bat" está contido na string
elemento_encontrado = s
break
if elemento_encontrado:
print(elemento_encontrado) # Sopa de batata doce
In this case, I stop as soon as I find any valid case (the use of break
interrupts the loop, that is, he stops at the first case he finds and does not even look at the rest). Then I just check if any string has actually been found and print it out.
You can still use a block else
in the for
, which is called if it is not interrupted by break
(that is, if no case is found):
for s in lista:
if busca in s: # se "de bat" está contido na string
elemento_encontrado = s
break
else:
print('Nenhum elemento encontrado')
Now if you will all the strings that contain the desired substring, you can use a comprehensilist on to return a list of all cases:
busca = 'a'
lista = ['Jorge Henrique', 'Matheus Oliveira Santos', 'Sopa de batata doce', 'Algorítimos maravilhosos']
# obtém uma lista com todas as strings que contém "a"
encontrados = [ s for s in lista if busca in s ]
print(encontrados) # ['Matheus Oliveira Santos', 'Sopa de batata doce', 'Algorítimos maravilhosos']
The line encontrados = [ s for s in lista if busca in s ]
is the comprehensilist on, and is equivalent to for
down below:
encontrados = []
for s in lista:
if busca in s:
encontrados.append(s)
But the comprehensilist on is more succinct and pythonic.
thank you very much, solved my problem here
– Jonathan Deptulsqui