Posts Tagged ‘new string formatting’

New string formatting syntax

April 4, 2011 2 comments

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: ,