Inserting string variables into print in python
18,050
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.
Related videos on Youtube
Comments
-
taronish4 almost 2 years
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')