I'm trying to check is any item of a list starts with a certain string. How could I do this with a for loop? IE:
anyStartsWith = False
for item in myList:
if item.startsWith('qwerty'):
anyStartsWith = True
Python example code use str. startswith() to find it a string starts with some string in a list. In the example list of substrings has converted into a tuple using tuple(list) in order to return a boolean if str contains substrings found it.
Method #1 : Using list comprehension + startswith() In this method, we use list comprehension for traversal logic and the startswith method to filter out all the strings that starts with a particular letter. The remaining strings can be used to make a different list.
Python Find String in List using count() We can also use count() function to get the number of occurrences of a string in the list. If its output is 0, then it means that string is not present in the list. l1 = ['A', 'B', 'C', 'D', 'A', 'A', 'C'] s = 'A' count = l1.
Use any()
:
any(item.startswith('qwerty') for item in myList)
Assuming you are looking for list items that starts with string 'aa'
your_list=['aab','aba','abc','Aac','caa']
check_start='aa'
res=[value for value in your_list if value[0:2].lower() == check_start.lower()]
print (res)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With