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.

Share:
18,050

Related videos on Youtube

taronish4
Author by

taronish4

UC Davis CSE student.

Updated on July 12, 2022

Comments

  • taronish4
    taronish4 almost 2 years

    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')