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:
1 2 3 |
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.
1 2 3 4 5 6 7 8 9 10 11 12 13 |
# 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:
1 2 3 4 5 6 7 8 9 10 11 |
+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.
1 2 3 4 5 6 7 8 9 10 11 12 13 14 |
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.
1 2 3 4 5 6 |
d = Data(20) print(format(d, 's')) print(format(d, 'i')) print(format(d, 'x')) |
Output:
1 2 3 4 5 6 7 8 |
__format__ method called Data[id=20] __format__ method called 20 __format__ method called invalid format spec |
Reference: Official Documentation