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
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.
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