0
astring = "Hello world!"
print(astring[3:7:2])

Python prints out "l". Can anyone explain to me why?

Adrian Mole
  • 49,934
  • 160
  • 51
  • 83

1 Answers1

2

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.

Green Cloak Guy
  • 23,793
  • 4
  • 33
  • 53
  • I appreciate your help, but I would like to understand what I can keep with this function, it doesn't make any sense for me – Andrea Careggio Jan 16 '21 at 17:04
  • If I write astring = "Hello world!" print(astring[3:7]) print(astring[3:7:1]) Python prints out "lo w". Why print out also " " and "w"? It should be prints out only "lo", shouldn't it? – Andrea Careggio Jan 16 '21 at 17:30
  • @AndreaCareggio, if you don't understand how string slicing works look at the link in ack's comment – KetZoomer Jan 16 '21 at 21:14
  • 1
    @AndreaCareggio the three parts of a slice are `start`, `stop`, and `step`, all of which are optional. The slice `[3:7:2]` means "start at index 3, stop before index 7, and increase by 2 each time - so we end up with the characters at indices `3` and `5`. Meanwhile, the slice `[3:7:1]` (or just `[3:7]`) only increases by 1 each time, so we get the characters at indices `3`, `4`, `5`, and `6`. – Green Cloak Guy Jan 17 '21 at 01:50