Search Substring In List In Python
I need to know if the letter b (both uppercase and lowercase preferably) consist in a list.
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)
- → What are the pluses/minuses of different ways to configure GPIOs on the Beaglebone Black?
- → Django, code inside <script> tag doesn't work in a template
- → React - Django webpack config with dynamic 'output'
- → GAE Python app - Does URL matter for SEO?
- → Put a Rendered Django Template in Json along with some other items
- → session disappears when request is sent from fetch
- → Python Shopify API output formatted datetime string in django template
- → Shopify app: adding a new shipping address via webhook
- → Shopify + Python library: how to create new shipping address
- → shopify python api: how do add new assets to published theme?
- → Access 'HTTP_X_SHOPIFY_SHOP_API_CALL_LIMIT' with Python Shopify Module