3

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.

vaultah
  • 44,105
  • 12
  • 114
  • 143
  • 2
    Look closely...they aren't actually the same. – jayelm May 04 '14 at 16:41
  • String formatting can be used in more contexts than just `print`. – roippi May 04 '14 at 16:42
  • 2
    In the latter case, the `print()` function is doing the work, so that syntax won't work anywhere except inside the `print()` function. In the former case, the string instance method is doing the work, so that will work anywhere you have a string. – Andrew Gorcester May 04 '14 at 16:57
  • Remove the `print` and look what makes more sense. – pepr May 04 '14 at 17:08
  • related: [Python string formatting: % vs. .format](http://stackoverflow.com/q/5082452/4279) – jfs May 04 '14 at 19:02
  • Possible duplicate of [Python string formatting: % vs. .format](https://stackoverflow.com/questions/5082452/python-string-formatting-vs-format) – Max Bethke Oct 05 '17 at 19:38

3 Answers3

7

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.

Paulo Bu
  • 29,294
  • 6
  • 74
  • 73
  • [`%` operator is not deprecated though `str.format()` is recommended instead](https://docs.python.org/3.4/library/stdtypes.html#printf-style-string-formatting) e.g., `logging` modules uses `%` formatting. – jfs May 04 '14 at 18:58
  • You're right, I thought I read that somewhere in the docs but evidences hint the contrary. Thanks for correcting, I'll edit the answer :) – Paulo Bu May 04 '14 at 23:53
2
>>> 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'
jfs
  • 399,953
  • 195
  • 994
  • 1,670
0

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.

disklosr
  • 1,536
  • 17
  • 26