Python Basics

This page contains some Python basics which are not well documented.

Rounding decimals with format strings

>>> n = 4
>>> p = math.pi
>>> '{0:.{1}f}'.format(p, n)
'3.1416'

the nested {1} takes the second argument, the current value of n, and applies it as specified (here, to the "precision" part of the format — number of digits after the decimal point), and the outer resulting {0:.4f} then applies. Of course, you can hardcode the 4 (or whatever number of digits) if you wish, but the key point is, you don't have to!

Even better…:

>>> '{number:.{digits}f}'.format(number=p, digits=n)
'3.1416'

…instead of the murky "argument numbers" such as 0 and 1 above, you can choose to use shiny-clear argument names, and pass the corresponding values as keyword (aka "named") arguments to format — that can be so much more readable, as you see!!!

This answer was written by Alex Martelli. For further details on format strings, see the Python Documentation

Difference between __str__ and __repr__ in Python

The simple answer by anonymous:

repr: representation of python object usually eval will convert it back to that object
str: is whatever you think is that object in text form

The detailed answer by Alex Martelli:

Unless you specifically act to ensure otherwise, most classes don't have helpful results for either:

>>> class Sic(object): pass
... 
>>> print str(Sic())
<__main__.Sic object at 0x8b7d0>
>>> print repr(Sic())
<__main__.Sic object at 0x8b7d0>
>>>

As you see — no difference, and no info beyond the class and object's id. If you only override one of the two…:

>>> class Sic(object): 
...   def __repr__(object): return 'foo'
... 
>>> print str(Sic())
foo
>>> print repr(Sic())
foo
>>> class Sic(object):
...   def __str__(object): return 'foo'
... 
>>> print str(Sic())
foo
>>> print repr(Sic())
<__main__.Sic object at 0x2617f0>
>>>

as you see, if you override repr, that's ALSO used for str, but not vice versa.

Other crucial tidbits to know: str on a built-on container uses the repr, NOT the str, for the items it contains. And, despite the words on the subject found in typical docs, hardly anybody bothers making the repr of objects be a string that eval may use to build an equal object (it's just too hard, AND not knowing how the relevant module was actually imported makes it actually flat out impossible).

So, my advice: focus on making str reasonably human-readable, and repr as unambiguous as you possibly can, even if that interferes with the fuzzy unattainable goal of making repr's returned value acceptable as input to eval!

This page contains content under license from http://www.stackoverflow.com

Unless otherwise stated, the content of this page is licensed under Creative Commons Attribution-ShareAlike 3.0 License