Start learning free

LESSON 61 OF 569 · STRINGS I

String Slicing in Python

Lesson

Not only we can select a single character from a string, but we can also select a sequence of consecutive characters (e.g. substring) from a string.

To achieve this, we use the the following syntax:

string[startIndex:endIndex]

This is called slicing a string. It returns the substring from startIndex to endIndex.

Here is an example:

language = "JavaScript"
substring = language[2:6]

print(substring) # Output: "vaSc"
print(language) # Output: "JavaScript"

The startIndex is a zero-based index at which we start extraction and the endIndex is also zero-based index before which we end the extraction.

The substring will not include the character at endIndex. You can see in our example that language[2] (v) was included while language[6] (r) was excluded.

Also notice that language preserved its value. The slicing does not affect the original string. It just creates a brand new one representing the sliced substring.


If you omit the endIndex, the slicing extracts to the end of the string:

language = "JavaScript"
substring = language[4:]

print(substring) # Output: "Script"

If you omit the startIndex, the slicing extracts from the start of the string:

language = "JavaScript"
substring = language[:4]

print(substring) # Output: "Java"

If you omit both startIndex and endIndex, the slicing extracts from the start to the end of the string. It basically clones the string:

language = "JavaScript"
substring = language[:]

print(substring) # Output: "JavaScript"


Assignment
Follow the Coding Tutorial and let's slice some strings!


Hint
Look at the examples above if you get stuck.


STEP 1 OF 3
    Ctrl + Enter to check