0

Something that should be very simple and yet I am not able to solve it. The indexing does not appear correctly when a character duplicates: For example:

list=[]
stringg="BAtmAn"
for i in stringg:
    if i.isupper():
        list.append(stringg.index(i))
print(list)

And the output shows [0,1,1] instead of [0,1,4]. When the stringg variable is changed to "BAtmEn" it appears the way I expect it to appear in the first example.

4
  • 1
    index returns the index of the first match unless you provide a start. Commented Oct 25, 2022 at 12:32
  • I noticed, what should I write instead Commented Oct 25, 2022 at 12:33
  • 1
    Try using enumerate instead. Example for index,letter in enumerate(stringg): if letter.isupper(): lst.append(index) Commented Oct 25, 2022 at 12:36
  • 2
    Note: don't use list as a variable name as it will conflict with the built in list class. Commented Oct 25, 2022 at 12:37

2 Answers 2

1

The following would do what you want

stringg="BAtmAn"
print([x for x in range(len(stringg)) if stringg[x].isupper()])
print([i for i, c in enumerate(stringg) if c.isupper()])
Sign up to request clarification or add additional context in comments.

Comments

0
list=[]
stringg="BAtmAn"
for i in range(len(stringg)):
    if stringg[i].isupper():
        list.append(i)
print(list)

should try this... .index('item') can only find the index of the first of that 'item' in the list.

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.