Python substring: how to cut or slice a string in Python

A string is a kind of list so you can get a letter of it by a specific index.

a = 'Apple'

print(a[0])  # A
print(a[1])  # p
print(a[2])  # p
print(a[3])  # l
print(a[4])  # e

The first char is at 0 index and the last char at 4 index. If writing a colon before an index (n), the value is the substring from the leading to the letter at index n.

a = 'Apple'

s = a[:2]

print(s)  # Ap

:2 means picking up the first 2 chars of Apple from the beginning. This style is called Python slicing. The following code shows how the index slices the original string.

a = 'Apple'

print(a[:0])  #
print(a[:1])  # A
print(a[:2])  # Ap
print(a[:3])  # App
print(a[:4])  # Appl
print(a[:5])  # Apple
print(a[:6])  # Apple

The first slicing (:0) means choosing 0 letter and creates the empty string. The slicing makes the substring whose length is the same as the number in the square brackets. 6 is bigger than the string's length so what choosing 6 letters is the same as what choosing 5 letters or the original string.

The above explanation of slicing gives you a hint of not only getting a substring but also selecting elements from a list in Python.

Last substring

If a colon is after a number (n), you get the substring from the char at n to the last char.

a = 'Apple'

s = a[2:]

print(s)  # ple

It can be regard as removing the first 2 chars from the original string. The number is 2 so the first 2 chars are removed. This may look strange but it's really helpful and pythonic.

a = 'Apple'

print(a[0:])  # Apple
print(a[1:])  # pple
print(a[2:])  # ple
print(a[3:])  # le
print(a[4:])  # e
print(a[5:])  #
print(a[6:])  #

The last substring is empty because Apple has only 5 letters.

Double colons

Using double colons, you can get the substring from a string with a specific step.

s = 'Facebook'

a = s[::1]
b = s[::2]
c = s[::3]
d = s[::4]

print(a)  # Facebook
print(b)  # Fcbo
print(c)  # Feo
print(d)  # Fb

Python String

Python Tutorial