Here's how we can shorten a string via slicing:
- Find the boundary:
>>> colon_position = title.index(':')
The index function locates a particular substring and returns the position where that substring can be found. If the substring doesn't exist, it raises an exception. This is always true of the result title[colon_position] == ':'.
- Pick the substring:
>>> discard_text, post_colon_text = title[:colon_position], title[colon_position+1:]
>>> discard_text
'Recipe 5'
>>> post_colon_text
' Rewriting, and the Immutable String'
We've used the slicing notation to show the start:end of the characters to pick. We also used multiple assignment to assign two variables, discard_text and post_colon_text, from two expressions.
We can use partition() as well as manual slicing. Find the boundary and partition:
>>> pre_colon_text, _, post_colon_text = title.partition(':')
>>> pre_colon_text
'Recipe 5'
>>> post_colon_text
' Rewriting, and the Immutable String'
The partition function returns three things: the part before the target, the target, and the part after the target. We used multiple assignment to assign each object to a different variable. We assigned the target to a variable named _ because we're going to ignore that part of the result. This is a common idiom for places where we must provide a variable, but we don't care about using the object.