Python format() function with Examples

Python format() function is used to convert given object into string representation based on the provided format specs.

Python format()

Python format() function syntax is:

This function calls __format__() method of the value object. We can define this function for our custom classes to use format() function with them.

Some of the format options for numbers are:

  • ‘+’ – sign should be used with both positive and negative numbers.
  • ‘-‘ – sign should be used with only negative numbers, this is the default behavior.
  • % – multiplied with 100 and shown in percentage
  • ‘b’, ‘o’, ‘x’, ‘X’ – convert integer to binary, octal and hexadecimal format. Lower case letters will be used for ‘x’ whereas upper case letters will be used with ‘X’. These are applicable only for integers.
  • ‘e’, ‘E’, ‘f’, ‘F’ – used with floating point numbers for Exponent notation and Fixed-point notation respectively

Let’s look at some examples of using format() function with numbers.

Output:

Python format() function for Custom Object

Let’s see how we can use format() function with custom object. We will create a class and define __format__() function for it. This function must return string otherwise we will get error.

Notice that I am formatting object based on the input format specification. If unrecognized format specs are provided, I am returning an error string. We can also throw an exception to be handled by the calling code.

Output:

You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

By admin

Leave a Reply

%d bloggers like this: