Question

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
Was it helpful?

Solution

Use any():

any(item.startswith('qwerty') for item in myList)

OTHER TIPS

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 want to do it with a for loop

anyStartsWith = False
for item in myList:
    if item[0:5]=='qwerty':
        anyStartsWith = True

the 0:5 takes the first 6 characters in the string you can adjust it as needed

Licensed under: CC-BY-SA with attribution
Not affiliated with StackOverflow
scroll top