Home > python > sprintf in Python 2

sprintf in Python 2

sprintf in Python

str = "pi is %.2f, name is %s" % (3.1415, "Boba")
print str   # pi is 3.14, name is Boba

Dictionary-based string formatting

myDict = {'solo': 'Han Solo', 
          'jabba': 'Jabba the Hutt'}
print "%(solo)s was captured by %(jabba)s." % myDict   # Han Solo was captured by Jabba the Hutt.

Values are taken from the dictionary myDict. In the pattern you need to specify the keys in parentheses.

What is it good for? It’s more readable because otherwise when you see “%s” you have to check on the right side what it is, then you jump back with your eyes, etc. Python programming is serious stuff, not to be confused with a table tennis match! :)


Dictionary-based string formatting with locals

A variation of the previous solution:

solo = 'Han Solo'
jabba = 'Jabba the Hutt'

print locals()   
# {'solo': 'Han Solo', '__builtins__': <module '__builtin__' (built-in)>, '__file__': './sprintf.py', 
#'__package__': None, 'jabba': 'Jabba the Hutt', '__name__': '__main__', '__doc__': None}

print "%(solo)s was captured by %(jabba)s." % locals()   # Han Solo was captured by Jabba the Hutt.

locals returns a copy of the local namespace as a dictionary where the keys are the variable names and the values are their respective values.

It means that in the pattern you can use the name of the variables and they will be replaced by their values.

About these ads
Categories: python Tags: , , ,
  1. No comments yet.
  1. No trackbacks yet.
You must be logged in to post a comment.
Follow

Get every new post delivered to your Inbox.

Join 63 other followers

%d bloggers like this: