Tip 30 Pick to str() or to repr()

Pythonic Programming — by Dmitry Zinoviev (39 / 116)

The Pragmatic Programmers
The Pragmatic Programmers

--

👈 Use Strings as Files | TOC | Remember, input() Remembers 👉

★★2.7, 3.4+ Every Python programmer knows about the built-in function str that converts any object to a string. Not every Python programmer knows about the built-in function repr that converts any object to a string. Even fewer Python programmers know about the difference, which seems nonexistent, at least for numbers:

​ str(123), repr(123), str(123.), repr(123.)​=> ​('122', '123', '123.0', '123.0')​

But what about strings? Function str still returns the original string (see Tip 74, Do Not str() a str), but repr returns the so-called canonical string representation of the argument:

​ str(​'123'​), repr(​'123'​)​=> ​('123', "'123'")​

Note the single quotation marks within the double quotation marks. They often make it possible to treat the canonical representation as a valid fragment of Python code. You can (but should not: Tip 87, Do Not eval(); It Is Evil) pass the canonical string to eval and hope to get the fully reconstructed original object:

​ eval(repr(​'hello'​))​=> ​'hello'​

The trick does not work with str — and even with repr, it often fails:

​ eval(str(​'hello'​))​=> ​Traceback (most…

--

--

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.