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.

6
  • 2
    Look closely...they aren't actually the same. Commented May 4, 2014 at 16:41
  • String formatting can be used in more contexts than just print. Commented May 4, 2014 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. Commented May 4, 2014 at 16:57
  • Remove the print and look what makes more sense. Commented May 4, 2014 at 17:08
  • related: Python string formatting: % vs. .format Commented May 4, 2014 at 19:02

3 Answers 3

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.

Sign up to request clarification or add additional context in comments.

2 Comments

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 :)
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' 

Comments

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.

1 Comment

Those extra blanks aren't necessary; print() already inserts them.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.