string formatting
right alignment
output formatting
text alignment
programming tutorial

Format output string, right alignment

Master System Design with Codemia

Enhance your system design skills with over 120 practice problems, detailed solutions, and hands-on exercises.

Introduction

Right-aligning text output is a common formatting task when building reports, printing tables, or displaying financial data in the terminal. Most programming languages provide built-in formatting tools that make right alignment straightforward. This article shows how to right-align strings and numbers in Python, Java, C++, and JavaScript, with practical examples for each.

Why Right Alignment Matters

Right alignment places content flush against the right edge of a fixed-width field, padding the left side with spaces (or another character). This is especially useful for numeric columns because it lines up digits by place value, making tables easier to scan.

 
1Left aligned:        Right aligned:
242                           42
31337                       1337
47                             7
5100000                   100000

Without right alignment, the digits do not line up and the table is harder to read at a glance.

Python

Python offers three approaches for right alignment: f-strings, the str.format() method, and the rjust() string method.

Using f-strings

python
1items = [("Widget", 42), ("Gadget", 1337), ("Bolt", 7), ("Gear", 100000)]
2
3print(f"{'Item':<10} {'Price':>10}")
4print("-" * 21)
5for name, price in items:
6    print(f"{name:<10} {price:>10}")

Output:

 
1Item           Price
2---------------------
3Widget            42
4Gadget          1337
5Bolt               7
6Gear          100000

The >10 format specifier means right-align within a 10-character field. The <10 means left-align. You can combine this with numeric formatting:

python
1value = 1234567.89
2
3# Right-align with comma separator and 2 decimal places
4print(f"{value:>20,.2f}")
5#        1,234,567.89

Using str.format()

python
1template = "{:<10} {:>10}"
2print(template.format("Item", "Price"))
3for name, price in items:
4    print(template.format(name, price))

Using rjust()

python
text = "42"
print(text.rjust(10))        # "        42"
print(text.rjust(10, "."))   # "........42"

The rjust() method pads the left side with spaces by default. You can pass a second argument to use a different fill character.

Java

Java provides String.format() and System.out.printf(), which follow the same format specifier syntax used in C's printf.

java
1public class RightAlignExample {
2    public static void main(String[] args) {
3        String[] names = {"Widget", "Gadget", "Bolt", "Gear"};
4        int[] prices = {42, 1337, 7, 100000};
5
6        System.out.printf("%-10s %10s%n", "Item", "Price");
7        System.out.println("-".repeat(21));
8
9        for (int i = 0; i < names.length; i++) {
10            System.out.printf("%-10s %10d%n", names[i], prices[i]);
11        }
12    }
13}

The %10d format specifier right-aligns an integer within a 10-character field. The %-10s left-aligns a string. Adding a comma flag formats numbers with thousand separators:

java
double amount = 1234567.89;
System.out.printf("%20,.2f%n", amount);
//        1,234,567.89

C++

C++ uses <iomanip> manipulators with std::cout for output formatting.

cpp
1#include <iostream>
2#include <iomanip>
3#include <string>
4#include <vector>
5
6int main() {
7    std::vector<std::pair<std::string, int>> items = {
8        {"Widget", 42}, {"Gadget", 1337}, {"Bolt", 7}, {"Gear", 100000}
9    };
10
11    std::cout << std::left << std::setw(10) << "Item"
12              << std::right << std::setw(10) << "Price" << std::endl;
13    std::cout << std::string(20, '-') << std::endl;
14
15    for (const auto& [name, price] : items) {
16        std::cout << std::left << std::setw(10) << name
17                  << std::right << std::setw(10) << price << std::endl;
18    }
19
20    return 0;
21}

Key points for C++ formatting:

  • std::setw(n) sets the field width. It only applies to the next output operation, so you must repeat it for each value.
  • std::right sets right alignment. It stays in effect until you change it with std::left.
  • std::setfill('0') changes the padding character from space to zero, useful for formatting IDs or timestamps.
cpp
int id = 42;
std::cout << std::setfill('0') << std::setw(6) << id << std::endl;
// Output: 000042

JavaScript

JavaScript's padStart() method handles right alignment for string output.

javascript
1const items = [
2  { name: "Widget", price: 42 },
3  { name: "Gadget", price: 1337 },
4  { name: "Bolt", price: 7 },
5  { name: "Gear", price: 100000 },
6];
7
8const header = "Item".padEnd(10) + "Price".padStart(10);
9console.log(header);
10console.log("-".repeat(20));
11
12for (const item of items) {
13  const line = item.name.padEnd(10) + String(item.price).padStart(10);
14  console.log(line);
15}

For numeric formatting with locale-aware separators:

javascript
1const amount = 1234567.89;
2const formatted = amount.toLocaleString("en-US", {
3  minimumFractionDigits: 2,
4  maximumFractionDigits: 2,
5});
6console.log(formatted.padStart(20));
7//        1,234,567.89

Note that padStart() works on strings, so you must convert numbers to strings before calling it.

Formatting Entire Tables

When building a complete table, compute the maximum width for each column dynamically rather than hardcoding field widths.

python
1data = [
2    ("Product", "Qty", "Total"),
3    ("Industrial Widget", 5, 125.50),
4    ("Bolt", 1000, 50.00),
5    ("Precision Gear Assembly", 2, 4999.99),
6]
7
8# Calculate column widths
9widths = [0] * len(data[0])
10for row in data:
11    for i, cell in enumerate(row):
12        widths[i] = max(widths[i], len(str(cell)))
13
14# Print with right-aligned numbers, left-aligned text
15for row in data:
16    parts = []
17    for i, cell in enumerate(row):
18        if isinstance(cell, (int, float)):
19            parts.append(str(cell).rjust(widths[i]))
20        else:
21            parts.append(str(cell).ljust(widths[i]))
22    print("  ".join(parts))

This approach adapts to any data and avoids truncation when values are wider than expected.

Common Pitfalls

  • Hardcoding field widths that are too narrow. If a value exceeds the specified width, most languages print the full value without padding rather than truncating it, which breaks alignment for the rest of the column.
  • Forgetting that std::setw() in C++ is consumed by the next output operation. Every value in a formatted row needs its own setw() call.
  • Mixing tabs and spaces for alignment. Tab widths vary between terminals and editors, so column alignment breaks unpredictably. Use spaces only.
  • Not converting numbers to strings before calling padStart() in JavaScript. Calling padStart on a number produces a TypeError.
  • Using right alignment for text columns. Names and labels are easier to read when left-aligned. Reserve right alignment for numbers and fixed-width codes.

Summary

Right alignment is handled by format specifiers (> in Python, %Nd in Java/C), stream manipulators (std::right in C++), or string methods (padStart in JavaScript, rjust in Python). Use it for numeric columns to line up digits by place value. Compute column widths dynamically when building tables, and always use spaces rather than tabs for consistent alignment across environments.


Course illustration
Course illustration

All Rights Reserved.