r/pythonhelp • u/OrganizationCalm7379 • May 10 '23
Need advice on a python problem
- Write a function named capital_indexes
- The function takes a single parameter, which is a string. Your function should return a list of all the indexes in the string that have capital letters.
- For example, calling capital_indexes("HeLlO")
should return the list [0, 2, 4]
This is the code I came up with:
def capital_indexes(string):
list = []
for i in string:
if i.isupper():
list.append(string.index(i))
return listThe issue I've been having is when I submit it returns " The call capital_indexes('TEsT') should return '[0, 1, 3]', but it returned '[0, 1, 0]' "
3
Upvotes
1
u/Zeroflops May 10 '23
The index will return the first index. So when you call it on the second “T” it’s returning the first location.
There are a couple of ways to do this. The first is to use a counter variable that you increment each pass. Then you can save that counter when you hit a capital.
Another way would be to increment over the index rather than the letters.
For i in len(string): then you check the char at position i
The more pythonic way is to use enumerate. For i, val in enumerate(string):
https://realpython.com/python-enumerate/
As a side note, try to avoid using variables like string, list, etc as they are key words in the language and will lead to issues. As you overwrite their functionality.