Advanced string formatting

| categories: python | tags: | View Comments

There are several more advanced ways to include formatted values in a string. In the previous case we examined replacing format specifiers by positional arguments in the format command. We can instead use keyword arguments.

s = 'The {speed} {color} fox'.format(color='brown', speed='quick')
print s
The quick brown fox

If you have a lot of variables already defined in a script, it is convenient to use them in string formatting with the locals command:

speed = 'slow'
color= 'blue'

print 'The {speed} {color} fox'.format(**locals())
The slow blue fox

If you want to access attributes on an object, you can specify them directly in the format identifier.

class A:
    def __init__(self, a, b, c):
        self.a = a
        self.b = b
        self.c = c

mya = A(3,4,5)

print 'a = {obj.a}, b = {obj.b}, c = {obj.c:1.2f}'.format(obj=mya)
a = 3, b = 4, c = 5.00

You can access values of a dictionary:

d = {'a': 56, "test":'woohoo!'}

print "the value of a in the dictionary is {obj[a]}. It works {obj[test]}".format(obj=d)
the value of a in the dictionary is 56. It works woohoo!.

And, you can access elements of a list. Note, however you cannot use -1 as an index in this case.

L = [4, 5, 'cat']

print 'element 0 = {obj[0]}, and the last element is {obj[2]}'.format(obj=L)
element 0 = 4, and the last element is cat

There are three different ways to “print” an object. If an object has a format function, that is the default used in the format command. It may be helpful to use the str or repr of an object instead. We get this with !s for str and !r for repr.

class A:
    def __init__(self, a, b):
        self.a = a; self.b = b

    def __format__(self, format):
        s = 'a={{0:{0}}} b={{1:{0}}}'.format(format)
        return s.format(self.a, self.b)

    def __str__(self):
        return 'str: class A, a={0} b={1}'.format(self.a, self.b)

    def __repr__(self):
        return 'representing: class A, a={0}, b={1}'.format(self.a, self.b)

mya = A(3, 4)

print '{0}'.format(mya)   # uses __format__
print '{0!s}'.format(mya) # uses __str__
print '{0!r}'.format(mya) # uses __repr__
a=3 b=4
str: class A, a=3 b=4
representing: class A, a=3, b=4

This covers the majority of string formatting requirements I have come across. If there are more sophisticated needs, they can be met with various string templating python modules. the one I have used most is Cheetah.

Copyright (C) 2013 by John Kitchin. See the License for information about copying.

org-mode source

blog comments powered by Disqus