Skip to main content

Slicing

beginner10 min readLesson 10 of 169

Extract pieces of text with [start:stop] — and the half-open rule.

Slicing takes a piece of a string: name[start:stop] — characters from start up to but not including stop:

word = "Python"
word[0:2]    # 'Py'
word[2:6]    # 'thon'
word[:3]     # 'Pyt'  (start defaults to 0)
word[3:]     # 'hon'  (stop defaults to end)
word[-3:]    # 'hon'  (negatives work too)

The half-open rule [start:stop) is the single most reused convention in Python — memorize it once, use it everywhere.

Step

An optional third number skips characters: word[::2] is 'Pto' (every second character). A step of -1 reverses: word[::-1] is 'nohtyP'.