+ 1
Why has difference in the index of two codes
s = "Hello" for i in s: print(s.index(i)) #___ print(s[0]) print(s[1]) print(s[2]) print(s[3]) print(s[4])
3 odpowiedzi
+ 1
>>> help("str.index")
str.index = index(...)
S.index(sub[, start[, end]]) -> int
Like S.find() but raise ValueError when the substring is not found.
So...it finds a substring.
>>> for i in s:
... print(s.index(i))
...
0 # find 'H'
1 # find 'e'
2 # first 'l'
2 # There's no difference between 'l' and 'l'
4 # 'o'
>>>
To find the second 'l' you have to distinguish between them, set the start parameter, use a command that allows for occurrence, etc.
+ 1
By the way:
Use enumerate() to extract indexes along with values.
http://stackoverflow.com/questions/522563/accessing-the-index-in-JUMP_LINK__&&__python__&&__JUMP_LINK-for-loops
0
If you were to change >s< to "Hello1" the first one would print "Hello1" the lower one would just print "Hello".
It might even crash if >s< is shorter than 5 chars