You can format the output of the print() function in Python using several methods. Here are the most common ways to format strings:
1. Using f-strings (Formatted String Literals)
Introduced in Python 3.6, f-strings allow you to embed expressions inside string literals using curly braces {}.
name = "Alice"
age = 30
print(f"Name: {name}, Age: {age}")
2. Using the str.format() Method
You can use the format() method to format strings. Place curly braces {} as placeholders in the string.
name = "Alice"
age = 30
print("Name: {}, Age: {}".format(name, age))
You can also specify the order of the arguments:
print("Age: {1}, Name: {0}".format(name, age))
3. Using Percent Formatting
This is an older method that uses the % operator to format strings.
name = "Alice"
age = 30
print("Name: %s, Age: %d" % (name, age))
4. Formatting Numbers
You can control the number of decimal places for floats and format integers in different ways.
pi = 3.14159
print("Pi rounded to 2 decimal places: {:.2f}".format(pi)) # Using format()
print(f"Pi rounded to 2 decimal places: {pi:.2f}") # Using f-string
number = 255
print("Binary: {:b}, Hex: {:x}".format(number, number)) # Binary and Hexadecimal
5. Using the format() Function with Width and Alignment
You can specify the width and alignment of the output.
name = "Alice"
print("{:<10} | {:>10}".format("Name", name)) # Left-align Name, right-align Alice
print("{:<10} | {:>10}".format("Age", 30))
Summary
You can format the output of the print() function using f-strings, the str.format() method, or percent formatting. You can also control the appearance of numbers and align text using width and alignment specifiers. These methods allow for flexible and readable output formatting in your Python programs.
