Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
613 views
in Technique[技术] by (71.8m points)

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"
See Question&Answers more detail:os

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

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)

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...