Home > Blockchain >  Wrong indexing of a string (Python)
Wrong indexing of a string (Python)

Time:10-25

Something that should be very simple and yet I am not able t 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. Please assist, thank you!

CodePudding user response:

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()])

CodePudding user response:

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.

  • Related