Building complicated strings from lists of characters
How can we make complicated changes to an immutable string? Can we assemble a string from individual characters?
In most cases, the recipes we've already seen give us a number of tools for creating and modifying strings. There are yet more ways in which we can tackle the string manipulation problem. In this recipe, we'll look at using a list
object as a way to decompose and rebuild a string. This will dovetail with some of the recipes in Chapter 4, Built-In Data Structures Part 1: Lists and Sets.
Getting ready
Here's a string that we'd like to rearrange:
>>> title = "Recipe 5: Rewriting an Immutable String"
We'd like to do two transformations:
- Remove the part before
:
- Replace the punctuation with
_
and make all the characters lowercase
We'll make use of the string
module:
>>> from string import whitespace, punctuation...