Python Tutorial
Python Flow Control
Python Functions
Python Data Types
Python Date and Time
Python Files
Python String
Python List
Python Dictionary
Python Variable
Python Input/Output
Python Exceptions
Python Advanced
In Python, there are several ways to format output for better readability and presentation. This tutorial covers the most commonly used methods: string concatenation, the %-formatting, the str.format()
method, and f-strings (formatted string literals).
+
operator to concatenate strings. However, this method can be inefficient and less readable when dealing with multiple variables or complex expressions.Example:
name = "Alice" age = 30 print("My name is " + name + " and I am " + str(age) + " years old.")
%
operator to substitute variables. This method is similar to the one used in C's printf
. However, it's considered somewhat outdated in modern Python.Example:
name = "Alice" age = 30 print("My name is %s and I am %d years old." % (name, age))
str.format()
method uses curly braces {}
as placeholders and the format()
function to substitute variables. It's more versatile and easier to read than %-formatting.Example:
name = "Alice" age = 30 print("My name is {} and I am {} years old.".format(name, age))
You can also use positional and keyword arguments to improve readability:
print("My name is {0} and I am {1} years old. {0} is a programmer.".format(name, age)) print("My name is {name} and I am {age} years old.".format(name="Alice", age=30))
f
or F
and include expressions inside curly braces {}
.Example:
name = "Alice" age = 30 print(f"My name is {name} and I am {age} years old.")
F-strings also support various formatting options, such as:
f"{variable:<10}"
(left-align), f"{variable:>10}"
(right-align), f"{variable:^10}"
(center-align)f"{variable:.2f}"
f"{variable:04d}"
(padding with zeros)Example:
pi = 3.1415926535 number = 42 print(f"Pi rounded to 2 decimal places: {pi:.2f}") print(f"Number padded with zeros: {number:04d}")
In summary, f-strings are the preferred method for formatting output in modern Python due to their readability, simplicity, and performance. However, it's essential to be familiar with other methods to work with older code or when using older versions of Python.
String formatting in Python:
name = "Alice" age = 25 formatted_string = "My name is {} and I am {} years old.".format(name, age) print(formatted_string)
Using f-strings for output formatting in Python:
name = "Bob" age = 30 formatted_string = f"My name is {name} and I am {age} years old." print(formatted_string)
Formatting numbers in Python output:
pi_value = 3.14159 formatted_number = "Value of pi: {:.2f}".format(pi_value) print(formatted_number)
Aligning text and numbers in Python output:
product = "Apple" price = 2.5 formatted_output = "{:<10} : {:.2f}".format(product, price) print(formatted_output)
Formatting dates and times in Python:
strftime
method to format dates and times.from datetime import datetime current_date = datetime.now() formatted_date = current_date.strftime("%Y-%m-%d %H:%M:%S") print(formatted_date)
Padding and spacing in Python output:
product = "Banana" quantity = 15 formatted_output = "{:10} : {:>5}".format(product, quantity) print(formatted_output)
Formatting lists and tuples in Python:
fruits = ['Apple', 'Banana', 'Orange'] formatted_list = "Fruits: {}".format(", ".join(fruits)) print(formatted_list)
Customizing output with format specifiers in Python:
quantity = 10 formatted_quantity = "Quantity: {:02d}".format(quantity) print(formatted_quantity)
Pretty printing in Python for better output readability:
pprint
module for more readable output of complex data structures.from pprint import pprint data = {'name': 'Charlie', 'age': 28, 'city': 'New York'} pprint(data)