How to return a list of all the indexes in the string that have capital letters?

Viewed 1941

I want to return a list of all the indexes in a string that have capital letters. So far I am able to create a list of all the values instead of their indices with a list comprehension. E.g. the string "HeLlO" should output [0, 2, 4]

Here's what I got:

def capital_indexes(str):
    return [x for x in str if x.isupper()]

Output is ['H', 'L', 'O']

2 Answers

Just use enumerate to get the indices:

def capital_indexes(string):
    return [i for i, char in enumerate(string) if char.isupper()]

print(capital_indexes("HeLlO")) # [0, 2, 4]

You can use this :

def capital_indexes(str_val):
    return [i for i in range(len(str_val)) if str_val[i].isupper()]

print(capital_indexes('HeLlO'))

PLEASE NOTE : Do not use str for your variable names . It is a reserved keyword .

Related