String Alignment in Python f-string
String alignment in Python helps make text look neat and organized, especially when printing data of different lengths. Without formatting, output can appear messy and hard to read. Python’s f-strings make it easy to align text by controlling its position within a set space. Python’s f-strings allow text alignment using three primary alignment specifiers:
- < (Left Alignment): Aligns the text to the left within the specified width.
- > (Right Alignment): Aligns the text to the right within the specified width.
- ^ (Center Alignment): Centers the text within the specified width.
Each alignment specifier is followed by a width number, which determines how much space is reserved for the string.
Example: Left-aligned (<), Right-aligned (>) and Center-aligned (^)
s = "Hello"
print(f"{s:<10}World")
print(f"{s:>10}World")
print(f"{s:^10}World")
Output
Hello World HelloWorld Hello World
Explanation: < specifier left-aligns “Hello”, so spaces are added to the right. The > specifier right-aligns “Hello”, meaning spaces are added before it. The ^ specifier centers “Hello”, adding an equal number of spaces on both sides.
Examples of String Alignment in Python f-strings
Example 1: Aligning Multiple Variables in a Table-Like Format
a = "Alice"
b = 25
# Left-aligned (<), Right-aligned (>), and Center-aligned (^)
print(f"Name: {a:<10} Age: {b:>5} ")
print(f"Name: {a:^10} Age: {b:^5} ")
Output
Name: Alice Age: 25 Name: Alice Age: 25
Explanation: “Alice” is left-aligned in 10 spaces and age 25 is right-aligned in 5 spaces for consistency. The second print statement centers both within their widths.
Example 2: Displaying List Data in a Structured Table
d = [("Alice", 25, "USA"), ("Char", 22, "Chicago")]
print(f"{'Name':<10}{'Age':<5}{'City':<10}")
for name, age, city in d:
print(f"{name:<10}{age:<5}{city:<10}")
Output
Name Age City Alice 25 USA Char 22 Chicago
Explanation: Column headers are left-aligned for a neat presentation. The loop aligns values within fixed-width columns, ensuring organized output with consistent spacing.
Example 3: Handling dynamic width
a = ["Apple", "Banana", "Cherry"]
max_width = max(len(word) for word in a) + 2
for word in a:
print(f"{word:<{max_width}} - Fruit")
Output
Apple - Fruit Banana - Fruit Cherry - Fruit
Explanation: max_width dynamically calculates the longest word’s length plus 2 spaces for padding, ensuring left-aligned, consistently spaced and readable output.
Example 4: String padding for enhanced formatting
s = "Python"
print(f"{s:-^20}")
print(f"{s:*<15}")
print(f"{s:=>15}")
Output
-------Python------- Python********* =========Python
Explanation: The first print statement centers “Python” within 20 spaces, filling the empty space with -. The second line left-aligns “Python” within 15 spaces, filling the remaining space with *. The third line right-aligns “Python” within 15 spaces, filling the left side with =.