If any item of list starts with string?
Asked Answered
F

3

16

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
Febri answered 8/10, 2012 at 14:23 Comment(0)
N
57

Use any():

any(item.startswith('qwerty') for item in myList)
Nardone answered 8/10, 2012 at 14:24 Comment(2)
Argh beat me to it! But yes this is the best way I think.Tyr
Thanks, that just about completes the validation of my last 72 hour of work!Febri
L
0

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

Limbourg answered 30/5, 2018 at 6:39 Comment(0)
E
0

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)
Eigenvalue answered 2/7, 2021 at 19:34 Comment(0)

© 2022 - 2024 — McMap. All rights reserved.