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
python - Finding substring in list of strings, return index - 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')
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.
There's a builtin method find on string objects.
s = "Happy Birthday"
s2 = "py"
print(s.find(s2))
Python is a "batteries included language" there's code written to do most of what you want already (whatever you want).. unless this is homework :)
find returns -1 if the string cannot be found.
Ideally you would use str.find or str.index like demented hedgehog said. But you said you can't ...
Your problem is your code searches only for the first character of your search string which(the first one) is at index 2.
You are basically saying if char[0] is in s, increment index until ch == char[0] which returned 3 when I tested it but it was still wrong. Here's a way to do it.
def find_str(s, char):
index = 0
if char in s:
c = char[0]
for ch in s:
if ch == c:
if s[index:index+len(char)] == char:
return index
index += 1
return -1
print(find_str("Happy birthday", "py"))
print(find_str("Happy birthday", "rth"))
print(find_str("Happy birthday", "rh"))
It produced the following output:
3
8
-1
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.