I have the following list and string:
lis = ['ejemplo 1', 'ejemplo 2', 'cualquier cosa']
palabra = 'ejemplo'
But when I do
palabra in lis
Returns False
. For what is this? How can I solve it?
I have the following list and string:
lis = ['ejemplo 1', 'ejemplo 2', 'cualquier cosa']
palabra = 'ejemplo'
But when I do
palabra in lis
Returns False
. For what is this? How can I solve it?
That happens because you're looking at the list and the 'ejemplo'
chain is not on the list as such. As you have it, your string palabra
is compared for each element in the list.
What you want is to see if the substring palabra
is within the strings contained in the list. To do this you must look for it within each element of the list. You can use any
for it:
>>> lis = ['ejemplo 1', 'ejemplo 2', 'cualquier cosa']
>>> palabra = 'ejemplo'
>>> any(palabra in string for string in lis)
You can follow the same logic to do other things:
If you want to know how many times it appears you can use:
>>> sum(palabra in string for string in lis)
If you want to see what strings they are and the index they occupy in the list you can use enumerate()
:
lis = ['ejempl2o 1', 'ejempl2o 2', 'cualquier cosa']
palabra = 'ejemplo'
res = [(indice, string)for indice, string in enumerate(lis) if palabra in string]
print(res)
Return us:
>>> [(0, 'ejemplo 1'), (1, 'ejemplo 2')]