Signup/Sign In

format() Method in Python- Part 1

Posted in Programming   LAST UPDATED: MARCH 15, 2021

    Python's built-in function format() is used to show output in a presentable manner and to substitute multiple values in a string output. It is a method that helps format strings, integers and various other types of values. It helps organize data and present it in a manner, that is pleasing to the eyes.

    For example: While showing database to users, using different kinds of formatters helps change alignment and show the data in a readable manner, without overwhelming the users.

    Template for the format function

    Following is the template for the format function,

    format(value, format_specification)

    Under the hood, the format function calls every object type's (which needs to be formatted) __format__ function.

    It is translated to: type(value).__format__(value, format_specification)

    The field to be replaced and the value with which it is replaced is placed in curly braces {} in a string. The format method is called on this string, which replaces the placeholder with specific values.

    Note: The string format method is a higher-level implementation of the format method. But both these methods use the __format__ method under the hood. In short, the string format method can perform much complex formatting processes on multiple string objects.

    First, we will look at the plain format method and then move on to the string format method.

    1. Formatting numbers

    While passing values to the format method, the type of value (like integer, floating, and binary) can be specified. This returns the same value. Suppose an integer is passed and the type is specified as a floating-point value, its equivalent floating value is displayed. But the opposite won't work, i.e passing a floating-point value and specifying the type as an integer will raise a ValueError since types can't be typecasted downward.

    Time for an example:

    print(format(13498, "d"))   # d specifies that the value passed is an integer
    print(format(342.763025, "f"))  # f specifies the value passed is a floating-point value
    print(format(12, "b"))   # b specifies the value passed is binary
    print(format(342.763025, "d"))

    Output:

    13498
    342.763025
    1100
    ValueError: Unknown format code 'd' for object of type 'float'

    2. Formatting numbers with different format specifiers:

    Below are a few format specifiers:

    fill - any character can be filled to a given number

    sign - This could be a +, - or blank space

    align - The alignment could be <, >, ^ or =

    precision - An integer that tells how precisely the value passed to format method has to be formatted.

    type - This specifies the type - binary, octal, exponential, etc. The other types will be listed in the upcoming post, as and when required.

    width - An integer value specifying how wide the value has to be formatted to.

    Time for an example:

    print(format(5839, "*<+8,d"))
    print(format(5839, "*>+8,f"))
    print(format(98.768065, "^-08.4f"))

    Output:

    +5,839**
    +5,839.000000
    98.76810

    We have covered more about the formatting of numbers using fill, sign, align, precision, type, width etc in a different post.

    3. Overriding __format__ while using the format method

    In the below example we will be overriding the __format__ method in a python class by defining its own __format__ method. Hence, when we will call the normal format() method on the object of the class defined, internally, it will run the __format__ method defined by us in the class.

    Time for an example:

    class StudyTonight:
        # custom format method
        def __format__(self, format):
            if(format == 'website'):
                return 'True'
            return 'False'
    
    print(format(StudyTonight(), "website"))
    print(format(StudyTonight(), "web"))

    Output:

    True
    False

    As you can see in the example above, we have overridden the __format__ method for our class Studytonight, which is called whenever we call format() method on the instance of our class.

    Conclusion

    In this post, we understood the various ways in which format method can be used to represent data in a readable and organized fashion. Run the code on your IDE, give different forms of input and observe the changes in the output. The next part of this post will give you more details on formatting strings and other data structures.

    Published by: SmritiSatyan
    Tags:PythonPython format
    IF YOU LIKE IT, THEN SHARE IT
     

    RELATED POSTS