简体   繁体   中英

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

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. Eg 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']

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 .

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM