3

I know of two ways to format a string:

  1. print 'Hi {}'.format(name)
  2. print 'Hi %s' % name

What are the relative dis/advantages of using either?

I also know both can efficiently handle multiple parameters like

print 'Hi %s you have %d cars' % (name, num_cars)

and

print 'Hi {0} and {1}'.format('Nick', 'Joe')
inspectorG4dget
  • 110,290
  • 27
  • 149
  • 241
taronish4
  • 504
  • 3
  • 5
  • 13
  • possible duplicate of [Python string formatting: % vs. .format](http://stackoverflow.com/questions/5082452/python-string-formatting-vs-format) – alecxe Aug 27 '13 at 21:40
  • There's yet another way to do this that may interest you which is using the [`string.Template`](http://docs.python.org/2/library/string.html?highlight=template#string.Template) class. I find the syntax more readable than plain `%` formating and most of `format`'s. Since it's a class you can derive your own specialized subclasses as well. – martineau Aug 27 '13 at 22:05

2 Answers2

1

There is not really any difference between the two string formatting solutions.

{} is usually referred to as "new-style" and %s is "old string formatting", but old style formatting isn't going away any time soon.

The new style formatting isn't supported everywhere yet though:

logger.debug("Message %s", 123)  # Works
logger.debug("Message {}", 123)  # Does not work. 

Nevertheless, I'd recommend using .format. It's more feature-complete, but there is not a huge difference anyway.

It's mostly a question of personal taste.

Thomas Orozco
  • 53,284
  • 11
  • 113
  • 116
0

I use the "old-style" so I can recursively build strings with strings. Consider...

'%s%s%s'

...this represents any possible string combination you can have. When I'm building an output string of N size inputs, the above lets me recursively go down each root and return up.

An example usage is my Search Query testing (Quality Assurance). Starting with %s I can make any possible query.

/.02

blakev
  • 4,154
  • 2
  • 32
  • 52