Skip to main content

5.5) Elements Of A String: Slicing


Sometimes you might want to access a range of elements in the string, not just one. We call this slicing. When slicing, you select a range of elements including the element at the start of the range, but excluding the last element of the range. Think of it as slicing at the boundary before the element indexed. Here’s an example:

[code lang="python"]
>>> my_string[4:8]
'o, W'
[/code]

Here 4:8 will return elements 4,5,6 and 7, but not 8! This may have been different in other languages you’ve used.

If you don’t specify the start of a range it will use the start of the string (element 0). If you don’t specify the end of the range, it will use the end of the string. So [:] is all the characters of the string.

[code lang="python"]
>>> my_string[:7]
'Hello,'
>>> my_string[7:]
'World!'
>>> my_string[:]
'Hello, World!'
[/code]