Sunday, January 12, 2025
HomeComputer SciencePython - Output Formatting

Python – Output Formatting

In Python, output formatting allows you to display data in a clean, organized, and readable manner. Below are the main methods and techniques for formatting output in Python:

1. Using f-strings (Python 3.6+)

F-strings are a concise and efficient way to format strings. They use curly braces {} to embed expressions directly in the string.

python
name = "Alice"
age = 25
print(f"My name is {name} and I am {age} years old.")

Output:
My name is Alice and I am 25 years old.

You can also format numbers:

python
pi = 3.14159
print(f"The value of pi is approximately {pi:.2f}.")

Output:
The value of pi is approximately 3.14.

2. Using str.format()

The str.format() method allows you to format strings by placing placeholders {} in the text.

python
print("My name is {} and I am {} years old.".format(name, age))

Output:
My name is Alice and I am 25 years old.

With positional or keyword arguments:

python
print("Hello, {0}! You are {1} years old.".format("Bob", 30))
print("Hello, {name}! You are {age} years old.".format(name="Carol", age=27))

3. Using the % Operator

This is an older method for string formatting using placeholders like %s, %d, or %f.

python
print("My name is %s and I am %d years old." % (name, age))

Output:
My name is Alice and I am 25 years old.

For floating-point precision:

python
print("The value of pi is approximately %.2f." % pi)

4. Using format() for Alignment and Padding

You can control alignment and width in output:

python
print("{:<10} {:>10}".format("Left", "Right")) # Left and right alignment
print("{:^10}".format("Center")) # Center alignment

Output:

mathematica
Left Right
Center

5. Using tabulate for Tabular Data (Optional Library)

For structured tabular output, the tabulate library is helpful.

bash
pip install tabulate
python
from tabulate import tabulate
data = [["Alice", 25], ["Bob", 30], ["Carol", 27]]
print(tabulate(data, headers=["Name", "Age"], tablefmt="grid"))

6. Using pprint for Pretty-Printing Data Structures

The pprint module is useful for printing nested data structures.

python
import pprint
data = {"name": "Alice", "age": 25, "skills": ["Python", "JavaScript"]}
pprint.pprint(data)

 

See also  What is Systems Design?

Choose the method that best fits your task! For most modern use cases, f-strings are the recommended approach due to their clarity and performance.

RELATED ARTICLES
0 0 votes
Article Rating

Leave a Reply

0 Comments
Oldest
Newest Most Voted
Inline Feedbacks
View all comments
- Advertisment -

Most Popular

Recent Comments

0
Would love your thoughts, please comment.x
()
x