...

/

Strings and Files Related Tips

Strings and Files Related Tips

Learn how string and file tips improve our code.

Pick to str() or to repr()

Let’s review some Python programmer preliminaries:

  • All of them know about the built-in str() function (converts any object to a string).
  • Not all of them know about the built-in repr() function (converts any object to a string).
  • Even fewer of them know about the difference, which seems nonexistent, at least for numbers:
Press + to interact
print(str(123),',', repr(123),',',str(123.),',',repr(123.))

What about strings? The str() function still returns the original string. The str(x) function is a string constructor, converting whatever x is into a string. This function never fails, but it doesn’t always do what we expect, and it’s not always needed. This function isn’t useful when applied to compound data structures, such as lists, dictionaries, sets, and generators. It displays either too many details or too few of them, (for more details, see Do not str() a str), but repr() returns the canonical string representation of the argument:

Press + to interact
print(str('123')," , ",repr("'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. We can pass the canonical string to eval() and hope to get the fully reconstructed original object:

eval(repr('hello')) The trick doesn’t work with str()—and often fails with repr():

Let’s evaluate str() function and observe its failure.

Press + to interact
eval(str('hello'))

Let’s evaluate repr() function and observe its failure.

Press + to interact
eval(repr(dir))

The repr() function, in a sense, attempts to reciprocate eval(): the ...