Search code examples
pythonstring-formatting

Can python's string format operator be applied to a class?


I was wondering if the string formatting operator , '%', can be applied to a class with subclasses in python, as seen below:

"I'm %(foo.name)s!" % class

I know it can be applied to a dictionary, but it doesn't seem to be able to access values in multidimensional dictionaries as far as I am aware.


Solution

  • You can't do % class but that shouldn't be troublesome because you will normally want to print a class instance. You can do what you want with a class instance. Given this class:

    class Foo():
        def __init__(self, name, id):
            self.name = name
            self.id = id
    

    you can do

    >>> foo = Foo("Bar",1)
    >>> f"I'm a {foo.name}"
    "I'm a Bar"
    

    or, if you're not using Python 3.7 yet

    >>> "I'm a {.name}".format(foo)
    "I'm a Bar"
    

    and if you really want to use the % operator

    >>> "I'm a %(name)s" % vars(foo)
    "I'm a Bar"