简体   繁体   中英

search substring in list in python

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"

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)

So the question is why doesn't this work?

Your list contains one big string, "apple, banana, Baboon, Charlie".

Add in the single quotes between elements.

Based on your latest comment, the code could be rewritten as:

count_total="".join(List1).lower().count('b')
if count_total:
   print "The letter b appears:", count_total, "times."
else:
   print "it did not work"

You basically join all the strings in the list and make a single long string, then lowercase it (since you don't care about case) and search for lowercase(b). The test on count_total works, because it evals to True if not zero.

The generator expression (element.lower().count('b') for element in List1) produces the length for each element. Pass it to sum() to add them up.

List1 = ['apple', 'banana', 'Baboon', 'Charlie']
num_times = sum(element.lower().count('b')
                for element in List1)
time_plural = "time" if num_times == 1 else "times"
print("b occurs %d %s"
      % (num_times, time_plural))

Output:

b occurs 3 times

If you want the count for each individual element in the list, use a list comprehension instead. You can then print this list or pass it to sum() .

List1 = ['apple', 'banana', 'Baboon', 'Charlie']
num_times = [element.lower().count('b')
             for element in List1]
print("Occurrences of b:")
print(num_times)
print("Total: %s" % sum(b))

Output:

Occurrences of b:
[0, 1, 2, 0]
Total: 3

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM