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?

2
  • 1
    Use enumerate() and iterate over both index and the character. Aug 9, 2015 at 20:41
  • 1
    After import re, [ match.start() for match in re.finditer('[A-Z]', "AuAskdjfIsjUsdhA") ] ==> [0, 2, 8, 11, 15]
    – Harvey
    Oct 21, 2015 at 21:12

1 Answer 1

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
3
  • 1
    Thanks, that's right what I was looking for!
    – Maslor
    Aug 9, 2015 at 21:12
  • 1
    No worries, you're welcome, no idea why you got downvoted, you supplied your code and a good attempt. Aug 9, 2015 at 21:15
  • 1
    I've seen it happen sometimes, as soon as someone flags a post as a duplicate, people automatically start down voting without even reading the question :/
    – Maslor
    Aug 9, 2015 at 22:06

Not the answer you're looking for? Browse other questions tagged or ask your own question.