astring = "Hello world!"
print(astring[3:7:2])
Python prints out "l". Can anyone explain to me why?
astring = "Hello world!"
print(astring[3:7:2])
Python prints out "l". Can anyone explain to me why?
It actually prints out l . You can see this if you convert the sliced string to a list of characters before printing it:
print(list(astring[3:7:2]))
['l', ' ']
This makes sense, because 'l' is the character at index 3, and ' ' is the character at index 5 (one step from 3, using step size 2). The character at index 7 is not printed because the 'end' index of a slice is exclusive, not inclusive, and 7 is not less than 7.