Lesson 02-03: Substrings with String Slicing¶
Learning Target: I can string slicing notation to reference substrings.
Substrings¶
We can use string indexing to get a single character from a string. Sometimes, though, we will want to get multiple letters, maybe a part of a string. Any “string within a string” is called a substring.
For example, the "pizza"
contains the substrings:
"piz"
"iz"
"izza"
"zz"
and so on (there’s more)!
String Slicing Notation¶
To get a substring from a string, we still use string indexing, but this time, instead of giving a single number in the []
brackets, we give a range - two numbers, separated by a colon. The syntax for string slicing is as follows:
some_string[a:b]
Where:
some_string
is the original stringa
is the index of where to begin slicing (includes this index)b
is the index of where to end slicing (excludes this index)
Let’s look at some examples:
The important thing to remember when slicing strings is that The range goes up to but does not include the second number.
What string slice would we have to use on “hippopotamus” to get the substring “ppopo”? Give you answer in the form [a:b], where a and b are numbers.
Special Python Syntax¶
Similar to how python has negative indexes, it also has some tricks for quick slicing. You don’t need to know this, but it might be helpful.
Special Syntax Meaning [:x]
The first x letters [:-x]
Everything except the last x letters [x:]
Everything except the first x letters [-x:]
The last x letters
Check For Understanding¶
Q#1¶
What string slice would we have to use on “How are you?” to get the substring “How”? Give your answer in the form [a:b]
, where a and b are numbers.
Q#2¶
What string slice would we have to use on “How are you?” to get the substring “are”? Give your answer in the form [a:b]
, where a and b are numbers.
Q#3¶
What string slice would we have to use on “How are you?” to get the substring “you”? Give your answer in the form [a:b]
, where a and b are numbers.
Q#4¶
What string slice would we have to use on any string to get the substring equal to the last 3 letters? Give your answer in the form []
, where anything can go between the brackets. (hint: use the special syntax above!)