1
Numbers, Strings, and Tuples
This chapter will look at some of the central types of Python objects. We’ll look at working with different kinds of numbers, working with strings, and using tuples. These are the simplest kinds of data that Python works with. In later chapters, we’ll look at data structures built on these foundations.
While these recipes start with a beginner’s level of understanding of Python 3.12, they also provide some deeper background for those familiar with the language. In particular, we’ll look at some details of how numbers are represented internally, because this can help when confronted with more advanced numerical programming problems. This will help us distinguish the uses cases for the rich variety of numeric types.
We’ll also look at the two different division operators. These have distinct use cases, and we’ll look at one kind of algorithm that demands truncated division.
When working with strings, there are several common operations that are important. We’ll explore some of the differences between bytes—as used by our OS files—and strings used to represent Unicode text. We’ll look at how we can exploit the full power of the Unicode character set.
In this chapter, we’ll show the recipes as if we’re working from the >>> prompt in interactive Python. This is the prompt that’s provided when running python from the command line or using the Python console in many Integrated Development Environment (IDE) tools. This is sometimes called the read-evaluate-print loop (REPL). In later chapters, we’ll change the style so it looks more like a script file. One goal of this chapter is to encourage interactive exploration because it’s a great way to learn the language.
We’ll cover these recipes to introduce basic Python data types:
Choosing between float, decimal, and fraction
Choosing between true division and floor division
String parsing with regular expressions
Building complicated strings with f-strings
Building complicated strings from lists of strings
Using the Unicode characters that aren’t on our keyboards
Encoding strings – creating ASCII and UTF-8 bytes
Decoding bytes – how to get proper characters from some bytes
Using tuples of items
Using NamedTuples to simplify item access in tuples
We’ll start with numbers, work our way through strings, and end up working with simple combinations of objects in the form of tuples and NamedTuple objects.