Ad

Search Substring In List In Python

- 1 answer

I need to know if the letter b (both uppercase and lowercase preferably) consist in a list.

My code:

List1=['apple', 'banana', 'Baboon', 'Charlie']
if 'b' in List1 or 'B' in List1:
    count_low = List1.count('b')
    count_high = List1.count('B')
    count_total = count_low + count_high   
    print "The letter b appears:", count_total, "times."
else:
    print "it did not work"
Ad

Answer

You need to loop through your list and go through every item, like so:

mycount = 0
for item in List1:
    mycount = mycount + item.lower().count('b')

if mycount == 0:
    print "It did not work"
else:
    print "The letter b appears:", mycount, "times"

Your code doesn't work since you're trying to count 'b' in the list instead of each string.

Or as a list comprehension:

mycount = sum(item.lower().count('b') for item in List1)
Ad
source: stackoverflow.com
Ad