Tip 74 Do Not str() a str

Pythonic Programming — by Dmitry Zinoviev (86 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Waste Space, Save Time | TOC | Chapter 6 Safety Tips 👉

★2.7, 3.4+ Function str(x) is a string constructor; it converts x, whatever it is, into a string. This function never fails, but it does not always do what you expect and is not always needed.

The function is not useful when applied to compound data structures, such as lists (Tip 36, Print a List), dictionaries, sets, and generators. It displays either too many details or too few of them.

The function is not needed when x is already a string. Converting a string to a string does not change the string but takes time (0.09 ms on my computer). So, do not.

Copyright © 2021, The Pragmatic Bookshelf.

👈 Waste Space, Save Time | TOC | Chapter 6 Safety Tips 👉

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.