1

I have this function that receives a word and lists the index of each capital letter:

def capitals(word):
    print word
    lst = []
    for i in word:
        if i.isupper():
            lst += [word.index(i)]
    return lst

When all capital letters in word are different, it runs fine. Example:

capitals("AuIkkdjsiP") returns [0,2,9]

However, if a string has duplicate capitals, this happens:

capitals("AuAskdjfIsjUsdhA") returns [0,0,10,0]

How do I get the index of the other occurrences of the char "A" when iterating the string?

Maslor
  • 1,821
  • 3
  • 20
  • 44

1 Answers1

4

You want enumerate to handle repeating characters, you can also use a list comprehension:

def capitals(word):
    return [i for i, ch in enumerate(word) if ch.isupper()]

ch is each character in the word, i is the index of the char.

On another note, if you want to add a single item to a list you should append not +=, if you have multiple elements to add it makes sense to +=/extend but for a single element just append :

def capitals(word):
    print word
    lst = []
    for i,ch in enumerate(word):
        if ch.isupper():
            lst.append(i)
    return lst
Padraic Cunningham
  • 176,452
  • 29
  • 245
  • 321