How to make a list of the indexes of capital letters in a word

Viewed 74

I'm trying to solve a challenge that I found online. It gives an input word and the expected output is a list of the indexes of all the capital letters. My program works unless there's duplicate capital letters. I can't figure out how to deal with it. Here's my code right now:

def capital_indexes(string):
    string = list(string)
    print(string)
    output = []

    for i in string:
        if i.isupper():
            output.append(string. index(i))
    return output

Like I said, it works for words like "HeLlO" but not for words like "TesT"

1 Answers

Try this one and compare the difference with OP:

You don't have to use index() method to search the character again, just use enumerate to get the tuple of (index, char) at the same time, and check if the character is capital case.

def capital_indexes(string):
    #string = list(string)   # string is an iterable! 
    #print(string)
    output = []

    for i, ch in enumerate(string):    # get index, char 
        if ch.isupper():
            output.append(i)
    return output
    
print(capital_indexes('TesT')) # [0, 3]
Related