Confused newbie here. What's the difference between using:
print ("So you are {0} years old".format(age)) AND
print ("So you are", age, "years old") Both work.
Actually there's a huge difference. The former use string's format method to create a string. The latter, pass several arguments to print function, which will concatenate them all adding a whitespace (default) between them.
The former is far more powerful, for instance, you can use the format syntax to accomplish things like:
# trunc a float to two decimal places >>> '{:.2f}'.format(3.4567) '3.46' # access an objects method >>> import math >>> '{.pi}'.format(math) '3.141592653589793' It is similar to printf style formats used in earlier versions of python with the % operator: (ie: "%d" % 3) Now str.format() is recommended over the % operator and is the new standard in Python 3.
% operator is not deprecated though str.format() is recommended instead e.g., logging modules uses % formatting.>>> class Age: ... def __format__(self, format_spec): ... return "{:{}}".format("format", format_spec) ... def __str__(self): ... return "str" ... >>> age = Age() >>> print(age) str >>> print("{:s}".format(age)) format format() allows to convert the same object into a string using different representations specified by format_spec. print uses __str__ or __repr__ if the former is not defined. format() may also use __str__, __repr__ if __format__ is not defined.
In Python 2 you could also define __unicode__ method:
>>> class U: ... def __unicode__(self): ... return u"unicode" ... def __str__(self): ... return "str" ... def __repr__(self): ... return "repr" ... >>> u = U() >>> print(u"%s" % u) unicode >>> print(u) str >>> print(repr(u)) repr >>> u repr There is also ascii() builtin function in Python 3 that behaves like repr() but produces ascii-only results:
>>> print(ascii("🐍")) '\U0001f40d' See U+1F40D SNAKE.
format() uses Format Specification Mini-Language instead of running various conversion to string functions.
An object may invent its own format_spec language e.g., datetime allows to use strftime formats:
>>> from datetime import datetime >>> "{:%c}".format(datetime.utcnow()) 'Sun May 4 18:51:18 2014' The former is more convenient. Imagine if you have lots of parameters, you'll end up with something like this:
print ("So your name is ", firstname, " ", lastname, " and you are ", age, " years old") This is a pain to both read and write. So the format method is there to help you write cleaner and more readable strings.
print() already inserts them.
print.print()function is doing the work, so that syntax won't work anywhere except inside theprint()function. In the former case, the string instance method is doing the work, so that will work anywhere you have a string.printand look what makes more sense.