The format() method used to return a formatted representation of the specified value. It is handled by the format specifier and inserts the formatted string inside the string's placeholder.The placeholders can be represented using numbered indexes {0},named indexes {price}, or even empty {}.The format() is similar to the 'String format' method, both methods call __format__() method of an object.
format(value[, format_spec]) #Where value can be a integer, float or binary format.
This function takes two parameters:In this format_spec could be in the format
[[fill]align][sign][#][0][width][,][.precision][type]
where, the options are
fill ::= any character
align ::= "<" | ">" | "=" | "^"
sign ::= "+" | "-" | " "
width ::= integer
precision ::= integer
type ::= "b" | "c" | "d" | "e" | "E" | "f" | "F" | "g" | "G" | "n" | "o" | "s" | "x" | "X" | "%"
Parameter | Description | Required / Optional |
---|---|---|
Value | The value that needs to be formatted | Required |
format_spec | The specification on how the value should be formatted. | Required |
Input | Return Value |
---|---|
format specifier. | formatted representation |
# d, f and b are type
# integer
print(format(123, "d"))
# float arguments
print(format(123.4567898, "f"))
# binary format
print(format(12, "b"))
Output:
123 123.456790 1100
# integer
print(format(1234, "*>+7,d"))
# float number
print(format(123.4567, "^-09.3f"))
Output:
*+1,234 0123.4570
# custom __format__() method
class Person:
def __format__(self, format):
if(format == 'age'):
return '23'
return 'None'
print(format(Person(), "age"))
Output:
23