Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Inserting string variables into print in python

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')
like image 924
taronish4 Avatar asked Dec 19 '25 21:12

taronish4


1 Answers

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.

like image 171
Thomas Orozco Avatar answered Dec 21 '25 11:12

Thomas Orozco