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')
2
  • possible duplicate of Python string formatting: % vs. .format Commented Aug 27, 2013 at 21:40
  • There's yet another way to do this that may interest you which is using the 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. Commented Aug 27, 2013 at 22:05

2 Answers 2

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.

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

Comments

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.