Explain Codes LogoExplain Codes Logo

Format output string, right alignment

python
string-formatting
f-strings
string-alignment
Anton ShumikhinbyAnton Shumikhin·Jan 15, 2025
TLDR

Here's the quick fix: use the str.format() or f-string syntax for right alignment. Here, > is your alignment operator:

formatted_text = "{:>20}".format("right-aligned") # or in the modern world of Python: formatted_text = f"{'right-aligned':>20}" print(formatted_text)

That 20 is your field width, ensuring the string struts its stuff right-aligned on that runway.

String alignment basics in Python

Python packs a punch with quite an array of tools for right alignment, bearing resemblance to C++ std::setw(). Python's str.format(), f-string, and rjust() provide a multitude of ways to give your text the perfect alignment.

  • str.format() with {:>width}:
# Me aligning my life priorities like: line = "Morning Run" formatted = "{:>30}".format(line) print(formatted) # Will I ever go for that run? Stay tuned.
  • f-string formatting:
# Python version 3.6+ > Upgrading life version description = "Productivity" width = 20 print(f'{description:>{width}}') # But first, let me take a coffee
  • rjust() method:
# I'm just right, said every string after using rjust() title = "Chapter 1" print(title.rjust(15, '.')) # Start of another "dot"iful journey

Exercise your Pythonic power: Unpack and align multiple values

# Consider this as String Avengers! values = ['Name', 3.14159, "A long story by Hemingway"] formatted_line = "{:>10} {:>10} {:>45}".format(*values) print(formatted_line) # Avengers, Assemble and right align!

The array values is unpacked into individual arguments for formatting, each right-aligned within its own defined character width.

When real-world collides with aligned strings

Crafting aligned columns in datasets

Data presentation is crucial, especially when handling text files representing tables or json configurations:

# Preparing a alignment banquet for strings headers = ["ID", "Name", "Price"] rows = [ [1234, "Widget", 19.99], [5678, "Gadget", 12.49], # More rows as your heart desires ] print(" | ".join(f"{h:>{10}}" for h in headers)) for row in rows: print(" | ".join(f"{str(c):>{10}}" for c in row))

Each column maintains a right-aligned posture, providing a clean and professional appearance much like a well-dressed butler.

Padding text display for client-side winning

UI and CLI interfaces often require elements to line up, like soldiers on a parade:

step_names = ["Download", "Install", "Configure", "Execute"] max_width = max(len(name) for name in step_names) for name in step_names: # My steps are aligned, now, if only my life would follow print(f"{name:>{max_width}} Progress: [----------]")

Efficient manipulation with string and expressions

In Python 3.6+, f-strings also support expressions within braces:

for i in range(1, 6): print(f"Value {i:<{2}}: {i**2:>{4}}") # Abstract nuances of life with Python f-string

Advanced tweaks for aligned strings

Peace within spaces

Let's delve into spacing nuances. Consider a receipt, your prices need to be right-aligned for legibility:

prices = [4.25, 10.99, 1000.5, 3.75] for p in prices: print(f"${p:>{10}}") # To pay or not to pay, that is the question

Handling long strings

Overflowing content? Python plans for that – no truncation, just lost alignment:

print(f"{'Python makes life easier':>15}") # The string is not cut off like my cable tv

String formatting is your aesthetic friend

In the realm of output strings, f-strings, & str.format() are not just tools, but paintbrushes:

from math import pi print(f"Pi is approximately {pi:.2f}.") # Serving precision on a silver platter