0

I'm trying to make a short program that will find all the capital letters in a single string. I got it to work for the first two capital letters but it won't return the correct position of the last capital letter. What did I do wrong?

def capital_indexes(n):
    listOfUpperPlaces = []
    for x in n:
        print(x)
        if x.isupper():
            characterPlace = n.index(x)
            print(characterPlace)
            listOfUpperPlaces.append(characterPlace)

    return listOfUpperPlaces

print(capital_indexes("TEsTo"))
Uft
  • 1
  • 1
  • 1
    Do you know what `index` does? – gspr Nov 13 '21 at 16:23
  • 2
    `n.index(x)` will return the first occurrence only. Use enumerate instead to go through the indexes along with the characters – rdas Nov 13 '21 at 16:24
  • See [Accessing the index in 'for' loops?](https://stackoverflow.com/q/522563/11082165) – Brian61354270 Nov 13 '21 at 16:24
  • `list.index` is a newbie trap. It is almost always the wrong tool for any job it's applied to - most of the time, `enumerate` is the right tool, and most of the rest of the time, a different data structure should be used. – user2357112 Nov 13 '21 at 16:39

2 Answers2

0

That is because n.index(x) returns the first occurrence of x in the string n. Because "T" occurs multiple times, n.index(x) returns the first occurrence of "T" You want to iterate through range(len(n), like

def capital_indexes(n):
listOfUpperPlaces = []
for x in range(len(n)):
    print(n[x])
    if n[x].isupper():
        print(x)
        listOfUpperPlaces.append(x)

return listOfUpperPlaces

print(capital_indexes("TEsTo"))

Max K
  • 41
  • 4
0

The issue is the call to n.index(x) This is searching the string to find x, and its able to find a capital T right at the beginning of the string.

A better way to do this would be to use enumerate, which gives you both the index and the item at the same time.

Can't code very well from a phone, but something like:

for index, character in enumerate(n):
    if character.isUpper():
        list_of_upper_places.append(index)

This will handle duplicates correctly, and will also be faster, since you don't need to search through the string just to count which character you are currently checking. It will be easier to read for most python programmers too.

Luke Nelson
  • 317
  • 2
  • 7