Python - Substring or Slice a String

1 min read

To create a substring or slice a string in Python you can use the slice syntax. Each character in a Python string has an index, just like items in a listHere's a visual representation of each letter's index number in the string 'hello'.

Using Python's slice notation you can tell Python which parts of the string you would like to access. 

s = "hello"

s[2]      # select item at index 2: 'l'
s[1:3]    # select from 1 to 3, excluding 3: 'el'
s[1:]     # select from 1 until end of string: 'ello'
s[:2]     # select from 0 to 2, excluding 2: 'he'

s[0:5:2]  # select from 0 to 4, skip every 2nd letter: 'hlo'

          # use - to select from right to left
s[-2]     # select 2nd last item: 'l'
s[-2:]    # select last 2 items: 'lo'
s[:-2]    # select all but last 2 items: 'hel'

s[::-1]   # all items, reversed: 'olleh'

# Usage example
first_two = s[:2]
# he

The key points to remember about this notation are that it uses a [start:stop:skip] pattern, the stop index is excluded from the selection, using a negative index number selects from right to left and setting setting skip to -1 will reverse the string.

Finally, if the above is a bit unclear, here's an example of how you can assign results of the above examples to a variable:

s = 'hello'
last_four = s[-4:]
# ello

Author picture
Rhett Trickett

Founder at Able

@rhett RhettTrickett rhetttrickett

Join the discussion

Able is a developer community where people build their coding knowledge and careers.

Join with GitHub Join with Twitter