Introduction
When writing Python programs, presenting output in a clean and organized manner is essential for both code readability and user experience. Whether you are creating reports, displaying tabular data, or simply printing information to the console, proper text alignment makes your output more professional and easier to read.
In this lab, you will learn various techniques to align and format text output in Python. You will explore different alignment methods, practice formatting techniques, and create well-structured tabular displays that can be applied in real-world applications.
Basic String Alignment in Python
In this first step, you will learn about the fundamental concepts of text alignment in Python and implement basic alignment techniques.
What is Text Alignment?
Text alignment refers to how text is positioned within a given space. Python provides several methods to control the positioning of text when printing to the console. The three main types of alignment are:
- Left alignment: Text starts from the left edge of the allocated space
- Right alignment: Text ends at the right edge of the allocated space
- Center alignment: Text is centered within the allocated space
Your First Alignment Program
Let's create a simple Python script to demonstrate the basic alignment techniques.
Open the WebIDE in your LabEx environment.
Create a new file named
basic_alignment.pyin the/home/labex/projectdirectory by clicking on the "New File" icon in the WebIDE.Add the following code to the file:
## basic_alignment.py
print("Basic String Alignment Examples")
print("-" * 30)
## Left alignment example
print("Left alignment:")
print("Python".ljust(20) + "|")
print("Programming".ljust(20) + "|")
print("Alignment".ljust(20) + "|")
print()
## Right alignment example
print("Right alignment:")
print("Python".rjust(20) + "|")
print("Programming".rjust(20) + "|")
print("Alignment".rjust(20) + "|")
print()
## Center alignment example
print("Center alignment:")
print("Python".center(20) + "|")
print("Programming".center(20) + "|")
print("Alignment".center(20) + "|")
Save the file by pressing
Ctrl+Sor by selecting "File" > "Save" from the menu.Open a terminal in the WebIDE (if not already open) by clicking on the "Terminal" menu and selecting "New Terminal".
Run the script using the Python interpreter:
cd ~/project
python3 basic_alignment.py
- You should see the following output:
Basic String Alignment Examples
------------------------------
Left alignment:
Python |
Programming |
Alignment |
Right alignment:
Python|
Programming|
Alignment|
Center alignment:
Python |
Programming |
Alignment |
Understanding the Code
The script you just created demonstrates three basic string alignment methods in Python:
- ljust(width): Left-justifies the string within a field of the specified width.
- rjust(width): Right-justifies the string within a field of the specified width.
- center(width): Centers the string within a field of the specified width.
In each example, we added a vertical bar (|) at the end of each line to clearly show the boundary of the allocated space. Notice how the text aligns differently in each case while maintaining the same total width of 20 characters.
String Alignment with Different Characters
The string justification methods can also take a second parameter to specify the fill character that will be used for padding. Let's modify our script to see this in action.
Create a new file named
alignment_with_chars.pyin the/home/labex/projectdirectory.Add the following code to the file:
## alignment_with_chars.py
print("String Alignment With Custom Characters")
print("-" * 40)
## Using different padding characters
print("Left alignment with dots:")
print("Python".ljust(20, '.') + "|")
print("Programming".ljust(20, '.') + "|")
print()
print("Right alignment with asterisks:")
print("Python".rjust(20, '*') + "|")
print("Programming".rjust(20, '*') + "|")
print()
print("Center alignment with hyphens:")
print("Python".center(20, '-') + "|")
print("Programming".center(20, '-') + "|")
- Save the file and run it:
python3 ~/project/alignment_with_chars.py
- You should see an output like this:
String Alignment With Custom Characters
----------------------------------------
Left alignment with dots:
Python..............|
Programming.........|
Right alignment with asterisks:
**************Python|
*********Programming|
Center alignment with hyphens:
-------Python------|
----Programming----|
These examples demonstrate how you can customize the appearance of your aligned text by using different padding characters.
Advanced Formatting Methods for Alignment
In the previous step, you learned about basic string alignment using the ljust(), rjust(), and center() methods. Now, let's explore more powerful and flexible formatting methods available in Python.
String Formatting Methods in Python
Python offers several ways to format strings:
- Old-style formatting (using the
%operator) - The
str.format()method - F-strings (formatted string literals, available in Python 3.6+)
Each method provides ways to align text and format various data types. Let's explore them one by one.
1. Old-style Formatting (% Operator)
This is the oldest method of string formatting in Python, similar to C's printf() function.
- Create a new file named
old_style_formatting.pyin the/home/labex/projectdirectory:
## old_style_formatting.py
print("Old-style String Formatting")
print("-" * 30)
## Left alignment with % formatting
print("Left aligned:")
print("%-15s | %-10s" % ("Python", "Language"))
print("%-15s | %-10s" % ("JavaScript", "Web"))
print()
## Right alignment with % formatting
print("Right aligned:")
print("%15s | %10s" % ("Python", "Language"))
print("%15s | %10s" % ("JavaScript", "Web"))
print()
## Numbers formatting
print("Number formatting:")
price = 125.5
tax_rate = 0.21
print("Price: $%8.2f" % price)
print("Tax rate: %6.1f%%" % (tax_rate * 100))
print("Tax amount: $%6.2f" % (price * tax_rate))
print("Total: $%8.2f" % (price * (1 + tax_rate)))
- Save the file and run it:
python3 ~/project/old_style_formatting.py
- You should see output similar to this:
Old-style String Formatting
------------------------------
Left aligned:
Python | Language
JavaScript | Web
Right aligned:
Python | Language
JavaScript | Web
Number formatting:
Price: $ 125.50
Tax rate: 21.0%
Tax amount: $ 26.36
Total: $ 151.86
2. The str.format() Method
The str.format() method provides a more versatile way to format strings and was introduced to address some limitations of the % operator.
- Create a new file named
format_method.pyin the/home/labex/projectdirectory:
## format_method.py
print("String Formatting with str.format()")
print("-" * 35)
## Basic alignment with format
print("Basic alignment:")
print("{:<15} | {:<10}".format("Python", "Language"))
print("{:>15} | {:>10}".format("Python", "Language"))
print("{:^15} | {:^10}".format("Python", "Language"))
print()
## Alignment with custom fill character
print("Custom fill character:")
print("{:*<15} | {:.>10}".format("Python", "Language"))
print("{:#^15} | {:=^10}".format("Python", "Language"))
print()
## Alignment with field names
print("Using field names:")
print("{name:<15} | {type:<10}".format(name="JavaScript", type="Web"))
print("{name:>15} | {type:>10}".format(name="Python", type="Language"))
print()
## Number formatting
price = 125.5
tax_rate = 0.21
print("Number formatting:")
print("Price: ${:8.2f}".format(price))
print("Tax rate: {:6.1f}%".format(tax_rate * 100))
print("Tax amount: ${:6.2f}".format(price * tax_rate))
print("Total: ${:8.2f}".format(price * (1 + tax_rate)))
- Save the file and run it:
python3 ~/project/format_method.py
- You should see output similar to this:
String Formatting with str.format()
-----------------------------------
Basic alignment:
Python | Language
Python | Language
Python | Language
Custom fill character:
Python********* | Language...
#####Python##### | ==Language==
Using field names:
JavaScript | Web
Python | Language
Number formatting:
Price: $ 125.50
Tax rate: 21.0%
Tax amount: $ 26.36
Total: $ 151.86
3. F-strings (Python 3.6+)
F-strings provide a concise and convenient way to embed expressions inside string literals. They are prefixed with the letter 'f' and use curly braces {} to include expressions.
- Create a new file named
f_strings.pyin the/home/labex/projectdirectory:
## f_strings.py
print("String Formatting with F-strings")
print("-" * 35)
language = "Python"
category = "Language"
version = 3.10
year = 2022
## Basic alignment with f-strings
print("Basic alignment:")
print(f"{language:<15} | {category:<10}")
print(f"{language:>15} | {category:>10}")
print(f"{language:^15} | {category:^10}")
print()
## Dynamic width specification
width1 = 15
width2 = 10
print("Dynamic width:")
print(f"{language:<{width1}} | {category:<{width2}}")
print(f"{language:>{width1}} | {category:>{width2}}")
print()
## Expressions inside f-strings
print("Expressions in f-strings:")
print(f"{'Python ' + str(version):<15} | {year - 1991:>10} years old")
print()
## Number formatting
price = 125.5
tax_rate = 0.21
print("Number formatting:")
print(f"Price: ${price:8.2f}")
print(f"Tax rate: {tax_rate * 100:6.1f}%")
print(f"Tax amount: ${price * tax_rate:6.2f}")
print(f"Total: ${price * (1 + tax_rate):8.2f}")
- Save the file and run it:
python3 ~/project/f_strings.py
- You should see output similar to this:
String Formatting with F-strings
-----------------------------------
Basic alignment:
Python | Language
Python | Language
Python | Language
Dynamic width:
Python | Language
Python | Language
Expressions in f-strings:
Python 3.1 | 31 years old
Number formatting:
Price: $ 125.50
Tax rate: 21.0%
Tax amount: $ 26.36
Total: $ 151.86
Comparison of Formatting Methods
Each formatting method has its advantages. Here's when to use each one:
- % Operator: Use in legacy code or when compatibility with older Python versions is necessary.
- str.format(): More powerful than % formatting, especially for complex formatting requirements.
- F-strings: The most concise and readable option, recommended for all new Python code (Python 3.6+).
The modern trend in Python is to use f-strings whenever possible due to their readability and performance benefits.
Creating Formatted Tables with Python
Now that you have learned different alignment techniques, let's apply them to create well-formatted tables. Tables are a common way to display structured data in a readable format, and proper alignment is crucial for presenting tabular information effectively.
Simple Table with Fixed Width Columns
Let's start by creating a simple table using fixed width columns.
- Create a new file named
simple_table.pyin the/home/labex/projectdirectory:
## simple_table.py
print("Simple Fixed-Width Table")
print("-" * 50)
## Define some data
header = ["Name", "Age", "City", "Profession"]
data = [
["John Smith", 34, "New York", "Doctor"],
["Sarah Johnson", 28, "San Francisco", "Engineer"],
["Michael Brown", 42, "Chicago", "Teacher"],
["Emily Davis", 31, "Boston", "Scientist"]
]
## Print header
print(f"{header[0]:<20} {header[1]:<8} {header[2]:<15} {header[3]:<15}")
print("-" * 60)
## Print rows
for row in data:
print(f"{row[0]:<20} {row[1]:<8} {row[2]:<15} {row[3]:<15}")
- Save the file and run it:
python3 ~/project/simple_table.py
- You should see a neatly formatted table like this:
Simple Fixed-Width Table
--------------------------------------------------
Name Age City Profession
------------------------------------------------------------
John Smith 34 New York Doctor
Sarah Johnson 28 San Francisco Engineer
Michael Brown 42 Chicago Teacher
Emily Davis 31 Boston Scientist
Dynamic Table with Multiple Alignment Types
Different types of data often look better with different alignment styles. For example, text is often left-aligned, while numbers are right-aligned. Let's create a more sophisticated table with mixed alignment.
- Create a new file named
dynamic_table.pyin the/home/labex/projectdirectory:
## dynamic_table.py
print("Dynamic Table with Mixed Alignment")
print("-" * 50)
## Define some data
header = ["Product", "Price", "Quantity", "Total"]
products = [
["Laptop", 1299.99, 3, 3899.97],
["Mouse", 24.50, 10, 245.00],
["Monitor", 349.95, 2, 699.90],
["Keyboard", 49.99, 5, 249.95],
["Headphones", 89.95, 4, 359.80]
]
## Calculate column widths based on content
col_widths = [
max(len(str(header[0])), max(len(str(row[0])) for row in products)) + 2,
max(len(str(header[1])), max(len(f"${row[1]:.2f}") for row in products)) + 2,
max(len(str(header[2])), max(len(str(row[2])) for row in products)) + 2,
max(len(str(header[3])), max(len(f"${row[3]:.2f}") for row in products)) + 2
]
## Print header
print(f"{header[0]:<{col_widths[0]}}"
f"{header[1]:>{col_widths[1]}}"
f"{header[2]:>{col_widths[2]}}"
f"{header[3]:>{col_widths[3]}}")
print("-" * sum(col_widths))
## Print rows with appropriate alignment
for product in products:
print(f"{product[0]:<{col_widths[0]}}",
f"${product[1]:.2f}".rjust(col_widths[1]),
f"{product[2]}".rjust(col_widths[2]),
f"${product[3]:.2f}".rjust(col_widths[3]))
## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * sum(col_widths))
print(f"{'TOTAL':<{col_widths[0]}}",
f"".rjust(col_widths[1]),
f"{total_quantity}".rjust(col_widths[2]),
f"${total_cost:.2f}".rjust(col_widths[3]))
- This code has an error that we need to fix. The formatting for the price and total columns is incorrect. Let's correct it:
## dynamic_table.py - corrected version
print("Dynamic Table with Mixed Alignment")
print("-" * 50)
## Define some data
header = ["Product", "Price", "Quantity", "Total"]
products = [
["Laptop", 1299.99, 3, 3899.97],
["Mouse", 24.50, 10, 245.00],
["Monitor", 349.95, 2, 699.90],
["Keyboard", 49.99, 5, 249.95],
["Headphones", 89.95, 4, 359.80]
]
## Calculate column widths based on content
col_widths = [
max(len(str(header[0])), max(len(str(row[0])) for row in products)) + 2,
max(len(str(header[1])), max(len(f"${row[1]:.2f}") for row in products)) + 2,
max(len(str(header[2])), max(len(str(row[2])) for row in products)) + 2,
max(len(str(header[3])), max(len(f"${row[3]:.2f}") for row in products)) + 2
]
## Print header
print(f"{header[0]:<{col_widths[0]}}"
f"{header[1]:>{col_widths[1]}}"
f"{header[2]:>{col_widths[2]}}"
f"{header[3]:>{col_widths[3]}}")
print("-" * sum(col_widths))
## Print rows with appropriate alignment
for product in products:
print(f"{product[0]:<{col_widths[0]}}",
f"${product[1]:.2f}".rjust(col_widths[1]),
f"{product[2]}".rjust(col_widths[2]),
f"${product[3]:.2f}".rjust(col_widths[3]))
## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * sum(col_widths))
print(f"{'TOTAL':<{col_widths[0]}}",
f"".rjust(col_widths[1]),
f"{total_quantity}".rjust(col_widths[2]),
f"${total_cost:.2f}".rjust(col_widths[3]))
- Save the corrected file and run it:
python3 ~/project/dynamic_table.py
- Let's simplify this example to make it more robust and easier to understand for beginners:
## dynamic_table.py - simplified version
print("Dynamic Table with Mixed Alignment")
print("-" * 50)
## Define some data
header = ["Product", "Price ($)", "Quantity", "Total ($)"]
products = [
["Laptop", 1299.99, 3, 3899.97],
["Mouse", 24.50, 10, 245.00],
["Monitor", 349.95, 2, 699.90],
["Keyboard", 49.99, 5, 249.95],
["Headphones", 89.95, 4, 359.80]
]
## Fixed column widths
product_width = 15
price_width = 12
quantity_width = 10
total_width = 12
## Print header
print(f"{header[0]:<{product_width}}"
f"{header[1]:>{price_width}}"
f"{header[2]:>{quantity_width}}"
f"{header[3]:>{total_width}}")
print("-" * (product_width + price_width + quantity_width + total_width))
## Print rows with appropriate alignment
for product in products:
print(f"{product[0]:<{product_width}}"
f"{product[1]:>{price_width}.2f}"
f"{product[2]:>{quantity_width}}"
f"{product[3]:>{total_width}.2f}")
## Print summary
total_quantity = sum(product[2] for product in products)
total_cost = sum(product[3] for product in products)
print("-" * (product_width + price_width + quantity_width + total_width))
print(f"{'TOTAL':<{product_width}}"
f"{'':{price_width}}"
f"{total_quantity:>{quantity_width}}"
f"{total_cost:>{total_width}.2f}")
- Save this simplified version over the previous file and run it:
python3 ~/project/dynamic_table.py
- You should see a well-formatted table like this:
Dynamic Table with Mixed Alignment
--------------------------------------------------
Product Price ($) Quantity Total ($)
-------------------------------------------------------
Laptop 1299.99 3 3899.97
Mouse 24.50 10 245.00
Monitor 349.95 2 699.90
Keyboard 49.99 5 249.95
Headphones 89.95 4 359.80
-------------------------------------------------------
TOTAL 24 5454.62
Creating a Financial Report
Now, let's create a more practical example - a financial report that uses alignment techniques for better readability.
- Create a new file named
financial_report.pyin the/home/labex/projectdirectory:
## financial_report.py
print("Monthly Financial Report")
print("=" * 60)
## Financial data
income_sources = [
["Salary", 5000.00],
["Freelance Work", 1200.50],
["Investments", 450.75],
["Other Income", 300.00]
]
expenses = [
["Rent", 1500.00],
["Utilities", 250.30],
["Groceries", 600.45],
["Transportation", 200.00],
["Insurance", 300.00],
["Entertainment", 150.25],
["Savings", 800.00],
["Miscellaneous", 300.00]
]
## Print Income Section
print("\nINCOME STATEMENT")
print("-" * 40)
print(f"{'Source':<20}{'Amount ($)':>20}")
print("-" * 40)
total_income = 0
for source, amount in income_sources:
total_income += amount
print(f"{source:<20}{amount:>20.2f}")
print("-" * 40)
print(f"{'Total Income':<20}{total_income:>20.2f}")
print()
## Print Expense Section
print("\nEXPENSE STATEMENT")
print("-" * 40)
print(f"{'Category':<20}{'Amount ($)':>20}")
print("-" * 40)
total_expenses = 0
for category, amount in expenses:
total_expenses += amount
print(f"{category:<20}{amount:>20.2f}")
print("-" * 40)
print(f"{'Total Expenses':<20}{total_expenses:>20.2f}")
print()
## Print Summary
print("\nMONTHLY SUMMARY")
print("-" * 40)
print(f"{'Total Income':<20}{total_income:>20.2f}")
print(f"{'Total Expenses':<20}{total_expenses:>20.2f}")
print("-" * 40)
balance = total_income - total_expenses
print(f"{'Net Balance':<20}{balance:>20.2f}")
## Add some conditional formatting for the balance
if balance > 0:
print(f"\nStatus: You saved ${balance:.2f} this month!")
else:
print(f"\nStatus: You overspent by ${-balance:.2f} this month.")
- Save the file and run it:
python3 ~/project/financial_report.py
- You should see a comprehensive financial report with nicely aligned columns:
Monthly Financial Report
============================================================
INCOME STATEMENT
----------------------------------------
Source Amount ($)
----------------------------------------
Salary 5000.00
Freelance Work 1200.50
Investments 450.75
Other Income 300.00
----------------------------------------
Total Income 6951.25
EXPENSE STATEMENT
----------------------------------------
Category Amount ($)
----------------------------------------
Rent 1500.00
Utilities 250.30
Groceries 600.45
Transportation 200.00
Insurance 300.00
Entertainment 150.25
Savings 800.00
Miscellaneous 300.00
----------------------------------------
Total Expenses 4101.00
MONTHLY SUMMARY
----------------------------------------
Total Income 6951.25
Total Expenses 4101.00
----------------------------------------
Net Balance 2850.25
Status: You saved $2850.25 this month!
This example shows how proper alignment can make complex financial information much easier to read and understand.
Key Takeaways
Through these examples, you've learned how to:
- Create simple fixed-width tables with consistent alignment
- Apply different alignment types based on data types (left for text, right for numbers)
- Create practical, real-world reports with clear visual organization
- Use string formatting methods to achieve precise control over output
These skills are valuable not just for console output but can be applied when generating reports, creating log files, or presenting data in any text-based format.
Summary
In this lab, you have learned various techniques for aligning and formatting text output in Python:
- Basic string alignment methods:
ljust(),rjust(), andcenter() - Different string formatting approaches: % operator,
str.format(), and f-strings - How to create well-structured tables with fixed-width columns
- How to apply different alignment styles based on data types
- How to create real-world applications like financial reports with proper formatting
These text alignment skills are essential for creating readable, professional output in many applications, from simple command-line utilities to complex data processing systems. By mastering text alignment in Python, you can significantly improve the user experience and readability of your programs.
As you continue your Python journey, remember that clean, well-formatted output is often as important as the computational logic of your programs. The techniques learned in this lab will help you present your data in a way that is both functional and visually appealing.



