-1
def finding_letters(s,l):

    i = 0
    while i < len(s):
        l = ''.join(l[i])
        a = s.find(l[i])
        return a
    i = i + 1

calling

finding_letters('abcde',['ab','cd','e'])

should give me an output of 0,2,4, but I only get output of 0.

Anything I could do to fix this?

Paul Rooney
  • 20,879
  • 9
  • 40
  • 61
noah
  • 1
  • please don´t use the facebook tag if it is not about facebook stuff. tag the programming language, for example. – andyrandy Nov 09 '16 at 17:10
  • Possible duplicate of [Finding multiple occurrences of a string within a string in Python](http://stackoverflow.com/questions/3873361/finding-multiple-occurrences-of-a-string-within-a-string-in-python) – Random Davis Nov 10 '16 at 23:15

2 Answers2

0

I'n not 100% sure what it is exactly that you're trying to do, but if you're trying to find the index of s where an element of l begins, here's one way.

s = 'abcde'
l = ['ab','cd','e']
l = [i[0] for i in l if i in s] #get the first letter of an element of l, but only if that element can be found in s 
output = [list(s).index(i) for i in l] #get the index of s where that element can be found 
print(output)                           
[0, 2, 4]
Alex Lang
  • 160
  • 1
  • 6
  • 1
    While this code may answer the question, providing additional context regarding why and/or how this code answers the question improves its long-term value. – Frerich Raabe Nov 10 '16 at 23:25
0

A simple generator approach can be used here:

>>> def find_letters(seq, l):
        for el in l:
            if not seq.find(el) == -1:
                yield seq.find(el)


>>> find_letters('abcde',['ab','cd','e'])
<generator object find_letters at 0x04305510>
>>> list(find_letters('abcde',['ab','cd','e']))
[0, 2, 4]
>>> 

Or better yet, a simpler generator expression:

>>> list(('abcde'.find(el) for el in ['ab','cd','e'] if 'abcde'.find(el) != -1))
[0, 2, 4]
>>> 
Christian Dean
  • 22,138
  • 7
  • 54
  • 87