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

15th Nov 2016, 3:28 PM
⾢ⴡ⾢ⴡ
⾢ⴡ⾢ⴡ - avatar
3 Answers
+ 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.
15th Nov 2016, 4:37 PM
Kirk Schafer
Kirk Schafer - avatar
16th Nov 2016, 10:23 AM
Kirk Schafer
Kirk Schafer - avatar
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
15th Nov 2016, 3:45 PM
Johannes K
Johannes K - avatar