Substrings
A substring is a smaller part of a larger string. In programming, you can use substrings to extract certain characters from a word, sentence, or input. This is useful when you only need part of the text, like initials, short codes, or sections of data.
How substrings work in Python
To get a substring, you give a start position and an end position using square brackets and a colon:
string[ start : end ]
Python counts positions starting at 0, and it takes characters from the start position up to, but not including, the end position.
This is because Python sees the string as a series of gaps between characters, like this:
| Index | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | ||||||||||
|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|---|
| Character | C | O | M | P | U | T | I | N | G | ||||||||||
| Position | 0 | 1 | 2 | 3 | 4 | 5 | 6 | 7 | 8 | 9 |
So word[2:5] includes characters at positions 2, 3, and 4.
Code examples
word = "computing" print(word[0:3]) # Output: com
# When the length of the string isn’t known, the len() function is useful for working out where to start your substring. word = "computing" last_pos = len(word) print( word[ last_pos-3 : last_pos ] ) # Output: ing
Exam Note
Python has other ways to get substrings, but when writing your answer for an exam, it’s clearest to use this format:
- string[ start : end ]