Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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('qwerty'):
        anyStartsWith = True
like image 924
tkbx Avatar asked Oct 08 '12 14:10

tkbx


People also ask

Can we use Startswith in list Python?

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.

How do you filter a string starting with Python?

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.

How do you check if a list contains a string in Python?

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.


2 Answers

Use any():

any(item.startswith('qwerty') for item in myList)
like image 129
Ashwini Chaudhary Avatar answered Oct 24 '22 19:10

Ashwini Chaudhary


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)
like image 27
Roshan Jha Avatar answered Oct 24 '22 21:10

Roshan Jha