Tuesday, 7 January 2025

Slicing strings in Python

 Background

Working with string is very common in any programming language and what comes in handy in Python is slicing. In this post, we will try to understand how slicing works for strings in Python.

Slicing in Python

The syntax for slicing is : Object [start:stop:step] where
  • "start" specifies the starting index of a slice 
  • "stop" specifies the ending element of a slice (not included)
  • "step" specifies the number of elements to jump/step on between start and stop.
Slicing can be done with negative indexes as well and if start/stop is negative that the indexes are counted from the end backward (See diagram below to understand the indexes - positive & negative).

See a few examples below
  
text = "ABCDE"
print(text[0:3])
print(text[0:3:2])
print(text[-4:-1])
print(text[-4:-1:2])

This prints:
ABC
AC
BCD
BD

You can also have the step as a negative number which will essentially consider elements backwards (reversing the data structure). See the following examples (more details on using this to reverse data structure are added in a later section).
  
text = "ABCDE"
print(text[3:0:-1])
print(text[3:0:-2])
print(text[::-1])
print(text[-1:-5:-1])

This prints:
DCB
DB
EDCBA
EDCB

NOTE: text[::] or text[:] is going to create a copy of the existing data structure.

Reversing Elements of Data Structure

You can use a negative step to reverse the elements of the following data structures

  
# list
l = ["a", "b", "c"]
print(l)
print(l[::-1])

# string
s = "abc"
print(s)
print(s[::-1])

# tuple
t = ("a", "b", "c")
print(t)
print(t[::-1])


This prints:
['a', 'b', 'c']
['c', 'b', 'a']
abc
cba
('a', 'b', 'c')
('c', 'b', 'a')

Cheat Sheet

  • a[start:stop]  # items start through stop-1
  • a[start:]      # items start through the rest of the array
  • a[:stop]       # items from the beginning through stop-1
  • a[:]           # a copy of the whole array
We can also pass step to the slicing which determines how many steps to jump for slicing
  • a[start:stop:step] # start through not past stop, by step
Step can also be a negative number
  • a[::-1]    # all items in the array, reversed
  • a[1::-1]   # the first two items, reversed
  • a[:-3:-1]  # the last two items, reversed
  • a[-3::-1]  # everything except the last two items, reversed

Related Links

t> UA-39527780-1 back to top