
Syntax: String Slicing
Getting part of a string with Python string slicing.
Getting a String Slice in Python
A very important skill when working with strings is the ability to take sections from a string that already exists and either use those sections by themselves, or combine them with other strings. In Python, a section of a string (a sub-string) is generally referred to as a string "slice". When you take a slice from a string it is also a string datatype.
The syntax for getting a string slice is similar to getting a character by its position and also uses bracket ([]) notation. The main difference is that you specify two indexes inside the square ([]) brackets (instead of one), separated by a colon (:):
print("Elbow grease"[2:5])
> bow
In the example above, the [2:5] is the range of the slice. It is the short-hand equivalent to getting the characters one-at-a-time and concatenating them:
material = "Elbow grease"
print(material[2] + material[3] + material[4])
> bow
Note that the slice does include the character at the first position, but does not include the character at the second position (material[2] is "b" and material[5] is " ").
Multiple slices can be concatenated together to effectively cut out part of a string:
material = "Elbow grease"
print(material[0:5] + material[6:12])
> "Elbowgrease"
When the slice starts at the beginning of a string, the first index can be left out:
print("Elbow grease"[:4])
> "Elbo"
Likewise, when the slice ends at the end of a string, the second index can be left out:
print("Elbow grease"[5:])
> " grease"
Leaving both out will duplicate the whole string:
print("Elbow grease"[:])
> "Elbow grease"
Like when working with single characters, negative indexes will start from the back:
print("Elbow grease"[-5:])
> "rease"
Practice: Slicing Strings
-
Create a variable named
phrase, and assign it the value"Make a long story short.". -
Using the
phrasevariable, print a slice from indexes5to10(not including10). -
Using the
phrasevariable, print a slice containing the word"long". -
Using the
phrasevariable, print a slice containing the last 10 characters. -
Using the
phrasevariable, print the entire string with all the"o"s sliced out.HINT*: Click here for a hint
> "a lon"
> "long"
> "ory short."
> "Make a lng stry shrt."
SOLUTION*: Click here for an example solution
phrase = "Make a long story short." print(phrase[5:10]) print(phrase[7:11]) print(phrase[-10:]) print(phrase[:8] + phrase[9:14] + phrase[15:20] + phrase[21:])
When the above steps are completed, you are ready to move to the next exercise!