Python format() function

Filed Under: Python

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:


format(value[, format_spec])

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.


# integers
print(format(10, '+'))
print(format(15, 'b'))

print(format(15, 'x'))
print(format(15, 'X'))

# float
print(format(.2, '%'))
print(format(10.5, 'e'))
print(format(10.5, 'e'))
print(format(10.5345678, 'f'))
print(format(10.5, 'F'))

Output:


+10
1111
f
F
20.000000%
1.050000e+01
1.050000e+01
10.534568
10.500000

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.


class Data:
    id = 0

    def __init__(self, i):
        self.id = i

    def __format__(self, format_spec):
        print('__format__ method called')
        if format_spec == 's':
            return "Data[id=%s]" % self.id
        if format_spec == 'i':
            return str(self.id)
        else:
            return 'invalid format spec'

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.


d = Data(20)
print(format(d, 's'))
print(format(d, 'i'))
print(format(d, 'x'))

Output:


__format__ method called
Data[id=20]
__format__ method called
20
__format__ method called
invalid format spec
You can checkout complete python script and more Python examples from our GitHub Repository.

Reference: Official Documentation

Leave a Reply

Your email address will not be published. Required fields are marked *

close
Generic selectors
Exact matches only
Search in title
Search in content
Search in posts
Search in pages