Now that you understand the basics of format specifiers, let's explore how to apply them in the print()
function.
The most common use of format specifiers is to insert values into the output string. You can use the format()
method to pass the values that will replace the format specifiers.
name = "LabEx"
age = 5
print("My name is {}, and I am {} years old.".format(name, age))
Output:
My name is LabEx, and I am 5 years old.
Controlling Alignment and Padding
You can also use format specifiers to control the alignment and padding of the output. This is useful when you want to create a well-formatted table or align values in a specific way.
print("| {:<10} | {:^10} | {:>10} |".format("Left", "Center", "Right"))
print("| {:-<10} | {:=^10} | {:->10} |".format("Left", "Center", "Right"))
Output:
| Left | Center | Right |
| Left-------- | =Center= | ------Right |
Format specifiers are particularly useful for formatting numeric values, such as integers, floats, and binary/octal/hexadecimal numbers.
print("Decimal: {:d}".format(42))
print("Binary: {:b}".format(42))
print("Octal: {:o}".format(42))
print("Hexadecimal: {:x}".format(42))
print("Float: {:.2f}".format(3.14159))
Output:
Decimal: 42
Binary: 101010
Octal: 52
Hexadecimal: 2a
Float: 3.14
By mastering the use of format specifiers in the print()
function, you can create highly customized and visually appealing output in your Python programs.