How to Pad Strings with Spaces in Python?

One of my team members asked me how to pad strings with spaces in Python. After researching various methods I found some important methods to achieve this task. Let us learn all the important methods in this tutorial with suitable examples and screenshots.

Pad Strings with Spaces in Python

String padding involves adding spaces (or other characters) to a string to ensure it reaches a specified length. This is particularly useful when aligning text in a table or creating a neat output format. In Python, you can pad strings using built-in methods such as ljust(), rjust(), and center().

Read How to Add Characters to a String in Python?

Method 1. Use ljust() Method

The ljust() method in Python pads a string with spaces (or a specified character) on the right side until it reaches a given width.

Example:

name = "John"
padded_name = name.ljust(10)
print(f"'{padded_name}'")

Output:

'John      '

I have executed the above example code and added the screenshot below.

Pad Strings with Spaces in Python

In this example, the name “John” is padded with spaces to ensure it has a total length of 10 characters.

Check out How to Iterate Through a String in Python?

Method 2. Use rjust() Method

Conversely, the rjust() method in Python pads a string with spaces on the left side.

Example:

name = "Doe"
padded_name = name.rjust(10)
print(f"'{padded_name}'")

Output:

'        Doe'

I have executed the above example code and added the screenshot below.

How to Pad Strings with Spaces in Python

Here, “Doe” is right-aligned with spaces added to its left.

Read How to Find the Last Occurrence of a Substring in a String Using Python?

Method 3. Use center() Method

The center() method in Python pads a string with spaces on both sides, centering the text within the specified width.

Example:

city = "Los Angeles"
padded_city = city.center(20)
print(f"'{padded_city}'")

Output:

'      Los Angeles      '

I have executed the above example code and added the screenshot below.

Pad Strings with Spaces in Python center()

In this case, “Los Angeles” is centered within a total width of 20 characters.

Check out How to Pad a String with Zeros in Python?

Method 4. Use format() Method

The format() method in Python allows you to pad a string with spaces (or other characters) by specifying a width.

Example:

name = "John"
padded_name = "{:<10}".format(name)
print(f"'{padded_name}'")

Output:

'John      '

I have executed the above example code and added the screenshot below.

Pad Strings with Spaces in Python format()

"{:<10}" means: < → Left-align the text. 10 → The total width of the string (including the original text and padding). The string "John" (4 characters) gets padded with 6 spaces on the right.

Check out How to Split a Long String into Multiple Lines in Python?

Pad with Custom Characters

While padding with spaces is common, you might want to use other characters. All three methods (ljust(), rjust(), and center()) allow you to specify a different fill character.

Example with Custom Character

product = "Widget"
padded_product = product.ljust(15, '-')
print(f"'{padded_product}'")

Output:

'Widget--------'

In this example, the string “Widget” is padded with dashes instead of spaces.

Read How to Extract Numbers from a String in Python?

Use Cases

Let us see some use cases for formatting tabular data and generating reports.

1. Format Tabular Data

When displaying tabular data, padding can help align columns. For instance, consider a simple list of USA cities and their populations:

data = [("New York", 8419600), ("Los Angeles", 3980400), ("Chicago", 2716000)]

print(f"{'City'.ljust(15)}{'Population'.rjust(10)}")
for city, population in data:
    print(f"{city.ljust(15)}{str(population).rjust(10)}")

Output:

City          Population
New York            8419600
Los Angeles         3980400
Chicago             2716000

This example demonstrates how padding helps maintain a clean and organized output.

Check out How to Format Decimal Places in Python Using f-Strings?

2. Generate Reports

When generating reports, padding can ensure that headers and data align correctly, making it easier for readers to understand the information presented. For instance:

report_title = "Monthly Sales Report"
print(report_title.center(50, '='))
print(f"{'Product'.ljust(20)}{'Sales'.rjust(10)}")
print("=" * 50)
print(f"{'Gadget A'.ljust(20)}{str(1500).rjust(10)}")
print(f"{'Gadget B'.ljust(20)}{str(2500).rjust(10)}")

Output:

====================Monthly Sales Report====================
Product              Sales
==================================================
Gadget A            1500
Gadget B            2500

Read How to Convert an Object to a String in Python?

Conclusion

In this tutorial, I have explained how to pad strings with spaces in Python. We have discussed some important methods to accomplish this task such as using the ljust() method, rjust() method, center() method, and format() method.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.