How to Substring a String in Python

Python offers many ways to substring a string. It is often called ‘slicing’.

It follows this template:

string[start: end: step]

Where,

start: The starting index of the substring. The character at this index is included in the substring. If start is not included, it is assumed to equal to 0.

end: The terminating index of the substring. The character at this index is NOT included in the substring. If end is not included, or if the specified value exceeds the string length, it is assumed to be equal to the length of the string by default.

step: Every ‘step’ character after the current character to be included. The default value is 1. If the step value is omitted, it is assumed to equal to 1.

Template

string[start:end]: Get all characters from index start to end-1

string[:end]: Get all characters from the beginning of the string to end-1

string[start:]: Get all characters from index start to the end of the string

string[start:end:step]: Get all characters from start to end-1 discounting every step character

Examples

Get the first 5 characters of a string

string = "freeCodeCamp"
print(string[0:5])

Output:

> freeC

Note: print(string[:5]) returns the same result as print(string[0:5])

Get a substring of length 4 from the 3rd character of the string

string = "freeCodeCamp"
print(string[2:6])

Output:

> eeCo

Please note that the start or end index may be a negative number. A negative index means that you start counting from the end of the string instead of the beginning (i.e from the right to left). Index -1 represents the last character of the string, -2 represents the second to last character and so on…

Get the last character of the string

string = "freeCodeCamp"
print(string[-1])

Output:

> p

Get the last 5 characters of a string

string = "freeCodeCamp"
print(string[-5:])

Output:

> eCamp

Get a substring which contains all characters except the last 4 characters and the 1st character

Our mission: to help people learn to code for free. We accomplish this by creating thousands of
videos, articles, and interactive coding lessons - all freely available to the public. We also have
thousands of freeCodeCamp study groups around the world.

Donations to freeCodeCamp go toward our education initiatives, and help pay for servers, services,
and staff.