Skip to content Skip to sidebar Skip to footer

Index Of Substring In A Python List Of Strings

How can I extract the index of a substring in a python list of strings (preferentially in a rapid way to handle long lists)? For example, with mylist = ['abc', 'day', 'ghi'] and ch

Solution 1:

You can use str.find with a list comprehension:

L = ['abc', 'day', 'ghi']

res = [i.find('a') for i in L]

# [0, 1, -1]

As described in the docs:

Return the lowest index in the string where substring sub is found within the slice s[start:end]. Optional arguments start and end are interpreted as in slice notation. Return -1 if sub is not found.


Solution 2:

Or with index

l = ['abc','day','ghi']
[e.index('a') if 'a' in l else -1 for e in l]

Post a Comment for "Index Of Substring In A Python List Of Strings"