Python: Iterate in a for and get as many objects in the list

0

I have a list of apple and pear products and I want to print on the screen how many apples there are by if but only print the "no apples". Where is the error and how can I fix it?

This is my code:

p = ["manzana_00", "manzana_01", "manzana_02",
     "pera_00", "pera_01", "pera_03"]

for i in p:

    if i == "manzana_*":
        print i + " es manzana"

    else:
        print "nada hay manzanas"
    
asked by jorgemorales 28.07.2016 в 01:14
source

1 answer

1

The problem is that as you are doing the comparison now, you are looking for the string i to be exactly equal to "manzana_ *" which is not true for any element in the list. What you could do is check if the item in the list contains the string "apple_" using in .

That would be done in the following way:

p = ["manzana_00", "manzana_01", "manzana_02",
     "pera_00", "pera_01", "pera_03"]

for i in p:

    if "manzana_" in i:
        print i + " es manzana"

    else:
        print "nada hay manzanas"

And now the result you would get is the following:

  

apple_00 is apple

     

apple_01 is apple

     

manzana_02 is apple

     

there are no apples

     

there are no apples

     

there are no apples

You can see how it works in this Python Fiddl e.

    
answered by 28.07.2016 / 02:11
source