How to search for partial text in a string list?

Asked

Viewed 379 times

1

I have a list with several text elements, and I would like to know how I can find one of these elements by searching for a part of the text and not by the exact text.

Example:

Lista = ['Jorge Henrique','Matheus Oliveira Santos','Sopa de batata doce','Algorítimos maravilhosos']

Now imagine that I want to find the element that contains 'de bat' which in case would be 'Sopa de batata doce'.

How can I find this way in Python and save in a variable?

2 answers

2


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.

2

Hello,

There are Python Association Operators in and not in, which are used to test whether a sequence is displayed on an object. You can check more about them here

For your solution you can do the following

resultado = [valor for valor in lista if 'de bat'  in valor ]

Browser other questions tagged

You are not signed in. Login or sign up in order to post.