XD blog

blog page

format, python, string

2014-08-26 string.format

It is just a trick about reducing the number of parameters to send to function format. Let's assume we have a class like the following:

class Entity:
    def __init__(self, name, city):
        self.name = name
        self.city = city
school = Entity("ENSAE", "Paris")

And we want to build a string like the following:

message = "school:{0} city:{1}".format(school.name, school.city)
# two parameters

But it could be rewritten as:

# one parameter
message = "school:{0.name} city:{0.city}".format(school)

<-- -->

Xavier Dupré