Thursday, April 19, 2012

Python string interpolation "fill in the blanks"

Here are some examples of "fill in the blanks" string formatting in Python. There are a thousand ways to skin this snake, and all of them work.

The examples shown all lead to the same result, errors are explained where appropriate:


>>> str1 = 'My favorite meal is %s and %s'
>>> str2 = 'My favorite meal is %(one)s and %(two)s'
>>> a = ('spam', 'more spam')    # note a is a tuple
>>> b = ['spam', 'more spam']    # note b is a list
>>> c1 = "one, two"
>>> c2 = "spam, more spam"
>>> d = {'one': 'spam', 'two': 'more spam'}   # note d is a dict
>>> e = dict(one = 'spam', two = 'more spam')  
>>> e
{'two': 'more spam', 'one': 'spam'}
>>> zip(c1.split(", "), c2.split(", "))
[('one', 'spam'), ('two', 'more spam')]
>>> f = dict(zip(c1.split(", "), c2.split(", ")))
>>> f
{'two': 'more spam', 'one': 'spam'}
>>> str1 % a
'My favorite meal is spam and more spam'
>>> str1 % b        # this doesn't work because b is only one argument
Traceback (most recent call last):  
  File "<stdin>", line 1, in <module> 
TypeError: not enough arguments for format string
>>> str1 % tuple(b)      # but this does, after making be a tuple
'My favorite meal is spam and more spam'
>>> str2 % d
'My favorite meal is spam and more spam'
>>> str2 % e
'My favorite meal is spam and more spam'
>>> str2 % f
'My favorite meal is spam and more spam'
>>> g = [('one', 'spam'), ('two', 'more spam')]
>>> h = {k:v for k,v in g}
>>> h
{'two': 'more spam', 'one': 'spam'}
>>> str2 % h
'My favorite meal is spam and more spam'
>>> i = dict((k,v) for k,v in g)
>>> i
{'two': 'more spam', 'one': 'spam'}
>>> str2 % i
'My favorite meal is spam and more spam'
>>> 

happy coding!

No comments:

Post a Comment