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
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
Use any()
:
any(item.startswith('qwerty') for item in myList)
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
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)
© 2022 - 2024 — McMap. All rights reserved.