Search code examples
pythonstringformatting

What does colon mean in Python string formatting?


I am learning the Python string format() method. Though I understand that {} is a placeholder for arguments, I am not sure what : represent in the following code snippet from Programiz tutorial:

import datetime
# datetime formatting
date = datetime.datetime.now()
print("It's now: {:%Y/%m/%d %H:%M:%S}".format(date))



# custom __format__() method
class Person:
    def __format__(self, format):
        if(format == 'age'):
            return '23'
        return 'None'

print("Adam's age is: {:age}".format(Person()))
  1. Why is there a : in front of %Y in print("It's now: {:%Y/%m/%d...? The code outputs It's now: 2021, and there is no : in front of 2021.
  2. Why is there a : in front of age in print("Adam's age is: {:age}...?

Thanks in advance for your valuable input!!


Solution

  • Python objects decide for themselves how they should be formatted using the __format__ method. Mostly we just use the defaults that come with the basic types, but much like __str__ and __repr__ we can customize. The stuff after the colon : is the parameter to __format__.

    >>> class Foo:
    ...     def __format__(self, spec):
    ...             print(repr(spec))
    ...             return "I will stubbornly refuse your format"
    ... 
    >>> f = Foo()
    >>> print("Its now {:myformat}".format(f))
    'myformat'
    Its now I will stubbornly refuse your format
    

    we can call the formatter ourselves. datetime uses the strftime format rules.

    >>> import datetime
    >>> # datetime formatting
    >>> date = datetime.datetime.now()
    >>> print("It's now: {:%Y/%m/%d %H:%M:%S}".format(date))
    It's now: 2021/10/04 11:12:23
    >>> date.__format__(":%Y/%m/%d %H:%M:%S")
    ':2021/10/04 11:12:23'
    

    Your custom Person class implemented __format__ and used the format specifier after the colon to return a value.