Skip to content Skip to sidebar Skip to footer

If Any Item Of List Starts With String?

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('q

Solution 1:

Use any():

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

Solution 2:

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)

Solution 3:

If you want to do it with a for loop

anyStartsWith = Falsefor 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

Post a Comment for "If Any Item Of List Starts With String?"