Last Updated
Viewed 957,506 Times

Python 2.6 introduced the str.format() method with a slightly different syntax from the existing % operator. Which is better and for what situations?

  1. The following uses each method and has the same outcome, so what is the difference?

    sub1 = "python string!"
    sub2 = "an arg"
    a = "i am a %s" % sub1
    b = "i am a {0}".format(sub1)
    c = "with %(kwarg)s!" % {'kwarg':sub2}
    d = "with {kwarg}!".format(kwarg=sub2)
    print a    # "i am a python string!"
    print b    # "i am a python string!"
    print c    # "with an arg!"
    print d    # "with an arg!"
  2. Furthermore when does string formatting occur in Python? For example, if my logging level is set to HIGH will I still take a hit for performing the following % operation? And if so, is there a way to avoid this?

    log.debug("some debug info: %s" % some_info)

Similar Question 1 : Python - Logger string formatting

As I understand it,

 'hello {0}'.format("world")

is slower than:

"hello %s" % "world"

My question is, how does logger format the strings when passed like so:

logger.debug("hello %s", "world")

And assuming the logs will never be turned off would it be better to do:

logger.debug("hello %s" % "world")

Similar Question 2 : python logging string formatting

I am using python's log formatter to format log records and i have a fmt value of

fmt = "[%(filename)s:%(lineno)s] %(message)s"

What i would like is that "[]" to be stretched to 10 characters wide (for example). If it was one value that would have been easy but is there any way to stretch this entire structure to a specified length? I want something like:

tmp = "[%(filename)s:%(lineno)s]"
fmt = "%(tmp)10s %(message)s"

I would like to know if this is possible using string formatting or if I can trick python's formatter somehow to get what i want..

Is there any string formatting for using correct suffix with log messages, for example:

for n in itertools.count():
  print 'printing for the {:nth} time'.format(n)

Expected output:

printing for the 0th time
printing for the 1st time
printing for the 2nd time
printing for the 3rd time
printing for the 4th time
printing for the 5th time
printing for the 23rd time
printing for the 42nd time

I could roll my own fairly easily, but I was wondering if there was already a built-in solution. If not, I will accept as answer the most elegant solution!

Similar Question 6 (2 solutions) : Using `str.format` to template log messages

Similar Question 8 (1 solutions) : How do I format logs so they print out in columns?

Similar Question 9 (1 solutions) : Python logging string not being formatter