chapter two

2 Strings

 

Strings in Python are the way in which we work with text. Words, sentences, paragraphs, and even entire files are read into and manipulated via strings. Because so much of our work revolves around text, it’s no surprise that strings are one of the most common data types.

There are two important things to remember about Python strings: (1) They are immutable, and (2) in Python 3, they contains Unicode characters, encoded in UTF-8. (See the sidebars on each of these subjects, below.)

There’s no such thing as a "character" type in Python; we can talk about a "one-character string," but that just means a string whose length is 1.

Python’s strings are interesting and useful not only because they allow us to work with text, but also because they’re a Python sequence. This means that we can iterate over them (character by character), retrieve their elements via numeric indexes, and search in them with the in operator.

This chapter contains exercises designed to help you work with strings in a variety of ways. The more familiar you are with Python’s string-manipulation techniques, the easier it will be to work with text.

2.1  Useful references

2.2  Pig Latin

2.2.1  Solution

2.2.2  Discussion

2.2.3  Beyond the exercise

2.3  Pig Latin sentence

2.3.1  Solution

2.3.2  Discussion

2.3.3  Beyond the exercise

2.4  Ubbi Dubbi

2.4.1  Solution

2.4.2  Discussion

2.4.3  Beyond the exercise

2.5  Sorting a string

2.5.1  Solution

2.5.2  Discussion

2.5.3  Beyond the exercise

2.6  Summary