Reputation: 524
I know of two ways to format a string:
print 'Hi {}'.format(name)
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')
Upvotes: 3
Views: 21348
Reputation: 4449
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
Upvotes: 0
Reputation: 55207
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.
Upvotes: 1