A non-slicky method:
def index_containing_substring(the_list, substring):
for i, s in enumerate(the_list):
if substring in s:
return i
return -1
Answer from kennytm on Stack Overflowpython - How to find indexes of string in lists which starts with some substring? - Stack Overflow
Index of substring in a python list of strings - Stack Overflow
Python get index of list in list of lists that contains a substring - Stack Overflow
string - Finding a substring within a list in Python - Stack Overflow
I know it's been a while since this question was active, but here's another solution anyways in case anyone is interested.
Your way seems fine, but here is a similar strategy, using the list.index() method:
starts = [lines.index(l) for l in lines if l.startswith('sub')]
As far as time goes, the two functions clock in at about the same (on average 1.7145156860351563e-06 seconds for your enumerate solution and 1.7133951187133788e-06 seconds for my .index() solution)
While I like your approach, here is another one that handles identical entries in lines correctly (i.e. similar to the way your sample code does), and has comparable performance, also for the case that the length of lines grows:
starts = [i for i in range(len(lines)) if lines[i].startswith('sub')]
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
subis found within the slices[start:end]. Optional argumentsstartandendare interpreted as in slice notation. Return-1ifsubis not found.
Or with index
l = ['abc','day','ghi']
[e.index('a') if 'a' in l else -1 for e in l]
use this function it will print the index
lst = [['Apple Pie', 'Carrot Cake'], ['Steak', 'Chicken']]
def function(list_contains,word_to_know):
for x in list_contains:
for y in x:
if word_to_know in y:
return list_contains.index(x)
print(function(lst,"Carrot"))
You can use something like this:
def find_index(l,c):
for i,v in enumerate(l):
for j in v:
if c in j:
return i
res = find_index(lst, 'Carrot')
print [s for s in list if sub in s]
If you want them separated by newlines:
print "\n".join(s for s in list if sub in s)
Full example, with case insensitivity:
mylist = ['abc123', 'def456', 'ghi789', 'ABC987', 'aBc654']
sub = 'abc'
print "\n".join(s for s in mylist if sub.lower() in s.lower())
All the answers work but they always traverse the whole list. If I understand your question, you only need the first match. So you don't have to consider the rest of the list if you found your first match:
mylist = ['abc123', 'def456', 'ghi789']
sub = 'abc'
next((s for s in mylist if sub in s), None) # returns 'abc123'
If the match is at the end of the list or for very small lists, it doesn't make a difference, but consider this example:
import timeit
mylist = ['abc123'] + ['xyz123']*1000
sub = 'abc'
timeit.timeit('[s for s in mylist if sub in s]', setup='from __main__ import mylist, sub', number=100000)
# for me 7.949463844299316 with Python 2.7, 8.568840944994008 with Python 3.4
timeit.timeit('next((s for s in mylist if sub in s), None)', setup='from __main__ import mylist, sub', number=100000)
# for me 0.12696599960327148 with Python 2.7, 0.09955992100003641 with Python 3.4
I don't think there is a good (i.e. readable) one-line solution for this. Alternatively to @eugene's loop, you could also use a try/except.
def get_index(list_of_strings, substring):
try:
return next(i for i, e in enumerate(list_of_strings) if substring in e)
except StopIteration:
return len(list_of_strings) - 1
The code is a little longer, but IMHO the intent is very clear: Try to get the next index that contains the substring, or the length of the list minus one.
Update: In fact, there is a good (well, somewhat okay-ish) one-liner, and you almost had it, using the default parameter of next, but instead of using the last element itself as default, and then calling index, just put the index itself and combine with enumerate:
next((i for i, e in enumerate(list_of_strings) if substring in e),
len(list_of_strings) - 1)
Using enumerate() in a function would be both more readable and efficient:
def get_index(strings, substr):
for idx, string in enumerate(strings):
if substr in string:
break
return idx
Note that you don't need to call .readlines() on a file object to iterate over the lines โ just use it as an iterable.
Hey. I'm trying to get the index position of the last character in a string. For example, if the string is "Hello" , I want the program to only print that the last character (in this case 'o') is in index position 4. The string would be inputted by the user though so its always going to be different.
I'm familiar with (len(string)) and string[-1] but not sure how to use them together, if I even need to.