Tip 15 Expand the Tabs

Pythonic Programming — by Dmitry Zinoviev (24 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Chain Comparison Operators | TOC | Pickle It 👉

★2.7, 3.4+ The character ’\t’ (tab space) is the only ASCII character whose visual representation is context sensitive. One can trace the symbol to the Ice Age of typewriters; the tabulator key would move the cartridge to the nearest tab stop. Advanced typewriters allowed users to define tab stops anywhere along the line, but the default (“cheap”) configuration was to keep them eight spaces apart.

Modern terminals mostly follow the same rules. They display ’\t’ as a sequence of one through seven characters, depending on how far the next tab stop position is, which makes it hard to align the output, especially when the distance between the tab positions is not known. Use method str.expandtabs(tabsize=8) to simulate the printout before it is displayed. The method expands each tab in the string by adding enough whitespace characters to reach the nearest tab stop. You can control the distance between the stops via the tabsize parameter:

​ ​'column1​​\t​​col2​​\t​​c3'​.expandtabs(8)​=> ​'column1 col2    c3'​

You can use str.expandtabs to calculate the width of a table or single string. Sadly, the method simulates only “cheap” typewriters; you cannot customize the individual stops.

👈 Chain Comparison Operators | TOC | Pickle It 👉

Pythonic Programming by Dmitry Zinoviev can be purchased in other book formats directly from the Pragmatic Programmers. If you notice a code error or formatting mistake, please let us know here so that we can fix it.

--

--

The Pragmatic Programmers
The Pragmatic Programmers

We create timely, practical books and learning resources on classic and cutting-edge topics to help you practice your craft and accelerate your career.