Python's built-in format() function is a string formatting method that inserts variables into strings and controls the output format.
Function Syntax
format(value, format_spec)
Parameters:
value: The value to format, which can be any data type such as integer, float, string, tuple, etc.format_spec: A string containing format instructions specifying the output format.
| Format Character | Meaning |
|---|---|
| 's' | String format. Default type for strings, can be omitted. |
| 'b' | Binary format. |
| 'c' | Character. Converts integer to corresponding Unicode character before printing. |
| 'd' | Decimal integer. Outputs base-10 numbers. |
| 'o' | Octal format. Outputs base-8 numbers. |
| 'x' | Hexadecimal format. Outputs base-16 numbers using lowercase letters for digits above 9. |
| 'X' | Hexadecimal format. Outputs base-16 numbers using uppercase letters for digits above 9. |
| 'n' | Number. Similar to 'd', but uses current locale to insert appropriate number separators. |
| 'e' | Exponential notation. Prints numbers in scientific notation using 'e' to indicate exponent. Default precision is 6. |
| 'E' | Exponential notation. Similar to 'e', but uses uppercase 'E' as separator. |
| 'f' | Fixed-point notation. Displays numbers as fixed-point decimals. Default precision is 6. |
| 'F' | Fixed-point notation. Similar to 'f', but converts nan to NAN and inf to INF. |
format() Function Examples
a = 123
b = 65
c = 88
print(format(a, 'b')) # Binary format
print(format(b, 'c')) # Convert to character
print(format(c, '010d')) # Decimal integer with leading zeros, width 10
print(format(a, 'x')) # Hexadecimal with lowercase letters
print(format(a, 'X')) # Hexadecimal with uppercase letters
print(format(b, 'e')) # Exponential notation, default precision 6
f-strings
In f-strings, curly braces {} serve as placeholders, directly embedding variables. Format instructions can be specified after a colon :. For example:
name = "Xiao Ming"
age = 18
formatted_str = f"I am {name}, I am {age:03d} years old."
print(formatted_str) # Output: "I am Xiao Ming, I am 018 years old."
In this example, {age:03d} specifies that age should be output as a decimal integer with width 3 and leading zeros.
__format__() Method
Calling format(value, format_spec) is transformed into type(value).__format__(value, format_spec):
class test:
def __init__(self):
self.number = 10
def __format__(self, format_spec):
if format_spec == 'x':
return str(hex(self.number))
return str(self.number)
a = test()
print(format(a, 'x'))
print(type(a).__format__(a, 'x'))
Output:
0xa 0xa
If an object doesn't properly define the __format__() method, or if __format__() doesn't return a string type, a TypeError will be raised.