I definitely prefer the format method more, as it is very flexible and can be easily extended to your custom classes by defining __format__ or str or repr . For ease of use, I use print in the following examples, which can be replaced with sys.stdout.write .
Simple examples: alignment / padding
#Justify / ALign (left, mid, right) print("{0:<10}".format("Guido")) # 'Guido ' print("{0:>10}".format("Guido")) # ' Guido' print("{0:^10}".format("Guido")) # ' Guido '
We can add, next to align parameters, which are ^ , < and > the fill character, to replace the space with any other character
print("{0:.^10}".format("Guido"))
Multiple Input Examples: Align and Fill Many Inputs
print("{0:.<20} {1:.>20} {2:.^20} ".format("Product", "Price", "Sum"))
Extended examples
If you have custom classes, you can define its str or repr views as follows:
class foo(object): def __str__(self): return "...::4::.." def __repr__(self): return "...::12::.."
Now you can use !s (str) or !r (repr) to tell python to call these specific methods. If nothing is defined, Python defaults to __format__ , which can also be overwritten. x = foo ()
print "{0!r:<10}".format(x)
Source: Python Base Link, David M. Baisley, 4th Edition
user1767754 Dec 12 '17 at 22:44 2017-12-12 22:44
source share