-1

This is my output:

0 1 2 3 2 5 6 7 8 3 5 11 2 6 7 8 3 2 5 11 20 21 22 23

I am not sure what exactly is going on here. I am obviously doing something incorrectly but what I that would be output would be

0 1 2 3 4 5 6 7 8 9 10 11 12 13 14 15 16 17 18 19 20 21 22 23

I am not sure why it is not in that order.

a = 'RqafaksdjfklasdjfaklEzty'

def w(s):
    str = ""
    for x in s:
        print(s.index(x))
    return str
w(a)
Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
Rick Perez
  • 69
  • 4
  • 2
    `index` returns the index of the FIRST appearance of the item. you have several `a`'s and the first one appears at index 2, so every time you see an `a` you will get 2. the same applies for any other repeating letter. but what are you trying to do? just get the length of a string? – Nullman Nov 07 '21 at 02:10
  • Specifically, what do you not understand? Don't just dump out two lists of numbers and expect us to figure it out. Please read [ask]. – ChrisGPT was on strike Nov 07 '21 at 02:10
  • Oh, I see now. That makes complete sense now. I didn't think of that @Nullman. I appreciate that answer. – Rick Perez Nov 07 '21 at 02:13
  • See the docs for [`index`](https://docs.python.org/3/library/stdtypes.html#str.index), which leads to the docs for [`find`](https://docs.python.org/3/library/stdtypes.html#str.find). If you want to loop over the characters _and_ print out their index, maybe [`enumerate`](https://docs.python.org/3/library/functions.html#enumerate) is what you want ([Accessing the index in 'for' loops?](https://stackoverflow.com/q/522563/2745495)). – Gino Mempin Nov 07 '21 at 02:15
  • A better duplicate which also answers your "why": [How to fix .index() method returning the wrong value?](https://stackoverflow.com/q/56712035/2745495) – Gino Mempin Nov 07 '21 at 02:20

2 Answers2

0

index only gets the first appearance of a string why don't use the range function for this?:

list(range(len(a)))
Pedro Maia
  • 2,666
  • 1
  • 5
  • 20
0

because when you use the .index() method, it will only return the first occurance of that item you are trying to find.

For example, when the loop is at index 4, where x = 'a', s.index('a') will return 2 instead of 4, since the first 'a' occured at index 2.

ir6
  • 95
  • 6