Home > python > New string formatting syntax

New string formatting syntax

I’m still using Python 2.6 but I think it’d be a good idea to start using the new string formatting syntax that was introduced in Python 3. Since it was backported to the 2.6 version, we can start using it right away.

Learn more:

This post is rather a reminder for me that I should read more about this topic. Later, I’ll add some examples too.

Update (20110704)

I asked a question about string formatting on python-list and got lots of useful answers. Here I’d make a short summary.

Old style, but still supported:

"the %s is %s" % ('sky', 'blue')

New style #1:

"the {0} is {1}".format('sky', 'blue')

New style #2, from Python 2.7+:

"the {} is {}".format('sky', 'blue')

New style #3, very useful for long string formattings:

"the {what} is {color}".format(what='sky', color='blue')

In new codes, I stopped using the old style. I use new style #1 and #3.

Related posts

Categories: python Tags: ,
  1. March 5, 2012 at 19:34

    What if you want to render curly braces?

    • March 5, 2012 at 20:59

      Double the braces. Example:

      >>> print 'the {what} is {color} {{}}'.format(what='sky', color='blue')
      the sky is blue {}
      
  1. No trackbacks yet.

Leave a comment