Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

I don't get what's the difference between format() and ... (python)

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.

like image 314
user3601794 Avatar asked Dec 30 '25 23:12

user3601794


2 Answers

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.

like image 119
Paulo Bu Avatar answered Jan 01 '26 12:01

Paulo Bu


>>> 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'
like image 20
jfs Avatar answered Jan 01 '26 13:01

jfs