Home > Software engineering >  It doesn't return the index of everysingle letter?
It doesn't return the index of everysingle letter?

Time:10-25

import re
def capital_indexes(string):
    cap=[]
    for i in string:
            if i.isupper()==True:
                    cap.append(string.find(i))
    return cap
print(capital_indexes("TEsT"))

I want it to return the index of every single letter that is a capital letter.

CodePudding user response:

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

print(capital_indexes("TEsT"))  #[0, 1, 3]

CodePudding user response:

str.find returns the index of the first value found. You have 2 T s, but it will return 0 for each. The enumerate function gives you the index of the value iterated, use that instead.

def capital_indexes(string):
    cap=[]
    for i,c in enumerate(string):
            if c.isupper()==True:
                    cap.append(i)
    return cap
print(capital_indexes("TEsT"))

CodePudding user response:

You should use enumerate() so that you are given the correct index without having to find it:

def capital_indexes(string):
    cap = []
    for idx,c in enumerate(string):
        if c.isupper():
            cap.append(idx)
    return cap
print(capital_indexes("TEsT"))

Output

[0, 1, 3]

CodePudding user response:

Or, without enumerate:

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

CodePudding user response:

find finds the first occurrence of the character in the String. Therefore, it returns [0, 1, 0]. Also there is no need for i.isupper()==True as i.isupper() in itself a boolean value.

def capital_indexes(string):
    cap=[]
    for num, char in enumerate(string):
            if char.isupper():
                    cap.append(num)
    return cap

print(capital_indexes("TEsT"))  #[0, 1, 3]

CodePudding user response:

The i iterator used in the for loop gives you the character, not the index.

String.find(i) will return the position of the character in the string.

You can simply append the character into the cap array instead of using string.find(i).

cap.append(i)

CodePudding user response:

You can also use list, filter and lambda:

def capital_indexes(s): 
    return list(filter(lambda i: s[i].isupper(), range(len(s))))

print(capital_indexes("TEsT"))

# [0, 1, 3]
  • Related