Try this approach using the newer str.format syntax. This uses a width of 12, space padded, right aligned.

line_new = '{:>12}  {:>12}  {:>12}'.format(words[0], words[1], words[2])

Example with the interpreter:

>>> line = "123 456 789"
>>> words = line.split(' ')
>>> line_new = '{:>12}  {:>12}  {:>12}'.format(words[0], words[1], words[2])
>>> print(line_new)
         123           456           789

And here's how to do it using the old % syntax (useful for older versions of Python that don't support str.format):

line_new = '%12s  %12s  %12s' % (words[0], words[1], words[2])
Answer from Mark Byers on Stack Overflow
Top answer
1 of 8
337

Try this approach using the newer str.format syntax. This uses a width of 12, space padded, right aligned.

line_new = '{:>12}  {:>12}  {:>12}'.format(words[0], words[1], words[2])

Example with the interpreter:

>>> line = "123 456 789"
>>> words = line.split(' ')
>>> line_new = '{:>12}  {:>12}  {:>12}'.format(words[0], words[1], words[2])
>>> print(line_new)
         123           456           789

And here's how to do it using the old % syntax (useful for older versions of Python that don't support str.format):

line_new = '%12s  %12s  %12s' % (words[0], words[1], words[2])
2 of 8
90

Here is another way how you can format using 'f-string' format:

print(
    f"{'Trades:':<15}{cnt:>10}",
    f"{'Wins:':<15}{wins:>10}",
    f"{'Losses:':<15}{losses:>10}",
    f"{'Breakeven:':<15}{evens:>10}",
    f"{'Win/Loss Ratio:':<15}{win_r:>10}",
    f"{'Mean Win:':<15}{mean_w:>10}",
    f"{'Mean Loss:':<15}{mean_l:>10}",
    f"{'Mean:':<15}{mean_trd:>10}",
    f"{'Std Dev:':<15}{sd:>10}",
    f"{'Max Loss:':<15}{max_l:>10}",
    f"{'Max Win:':<15}{max_w:>10}",
    f"{'Sharpe Ratio:':<15}{sharpe_r:>10}",
    sep="\n"
)

This will provide the following output:

Trades:              2304
Wins:                1232
Losses:              1035
Breakeven:             37
Win/Loss Ratio:      1.19
Mean Win:           0.381
Mean Loss:         -0.395
Mean:               0.026
Std Dev:             0.56
Max Loss:          -3.406
Max Win:             4.09
Sharpe Ratio:      0.7395

What you are doing here is you are saying that the first column is 15 chars long and it's left-justified and the second column (values) is 10 chars long and it's right-justified.

If you joining items from the list and you want to format space between items you can use `` and regular formatting techniques.

This example separates each number by 3 spaces. The key here is f"{'':>3}"

print(f"{'':>3}".join(str(i) for i in range(1, 11)))

output:

1   2   3   4   5   6   7   8   9   10
🌐
GeeksforGeeks
geeksforgeeks.org › python › string-alignment-in-python-f-string
String Alignment in Python f-string - GeeksforGeeks
July 15, 2025 - Explanation: max_width dynamically calculates the longest word's length plus 2 spaces for padding, ensuring left-aligned, consistently spaced and readable output. ... 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 =.
🌐
LabEx
labex.io › tutorials › python-how-to-align-output-in-python-printing-418802
How to align output in Python printing | LabEx
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.py in the /home/labex/project directory by clicking on the "New File" icon in the WebIDE. ... ## 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) + "|")
🌐
Scientifically Sound
scientificallysound.org › 2016 › 10 › 17 › python-print3
Take control of your Python print() statements: part 3 | Scientifically Sound
November 17, 2021 - If we are dealing with our first item (i.e., i = 0), we tell Python that we want to print a line of dashes, then print our headers, followed by another line of dashes. Notice how we specify the number of spaces we want for each header as well as the alignment of the text.
🌐
Delft Stack
delftstack.com › home › howto › python › python print column alignment
How to Print With Column Alignment in Python | Delft Stack
February 22, 2025 - For basic text formatting, format() or f-strings are the best options. For structured tabular data, tabulate and pandas provide automated formatting that ensures consistent alignment. If you’re working with matrices, check out Printing Matrices in Python for more structured output techniques.
🌐
Medium
medium.com › @pivajr › pythonic-tips-how-to-align-strings-to-the-left-right-and-center-in-python-557db734cce6
Pythonic Tips: How to Align Strings to the Left, Right, and Center in Python | by Dilermando Piva Junior | Medium
May 22, 2025 - Pro tip: For internationalized systems, combine these methods with the locale library to respect cultural conventions (e.g., right-aligned numbers). Want to design a digital certificate or text-based art? The fill parameter (in classic methods) and : operator (in f-strings) let you replace whitespace with custom characters: event = "PyCon Brazil 2024" print(f"\n{event:_^40}\n") print(" Pythonista, ".center(40, '☆')) print(" You’re invited to ".center(40, '☆')) print("the biggest Python celebration in the country!".center(40, '☆')) print("\n" + "Join us: Oct 25–27 | São Paulo".rjust(40, '•'))
🌐
Towards Data Science
towardsdatascience.com › home › programming › formatting strings and numbers in python
Formatting strings and numbers in python | Towards Data Science
June 27, 2021 - You can use the :>, :< or :^ option in the f-format to left align, right align or center align the text that you want to format.
🌐
Reddit
reddit.com › r/learnpython › how to align text with formatting?
r/learnpython on Reddit: How to align text with formatting?
February 8, 2022 -

This is a very basic question, I am in a beginner python course. I am trying to figure out how to align text in print results, but can not for the life of me figure out how to do it properly.

print('\tBoat Repair Program')

#Get input from user.

boatprice = float(input('\nWhat was the initial cost of the boat? $'))

hourfix = float(input('How many hours were spent fixing the boat? $'))

payrate = float(input('What is the hourly pay rate? $'))

partcost = float(input('What was the cost of repair parts for the boat? $'))

#Calculate total repair cost.

totalcost = (hourfix * payrate) + partcost

#Calculate the final value.

finalvalue = boatprice + totalcost

#Print results.

print(f'\nInitial purchase price: ${boatprice:,.2f}'),

print(f'The total cost of repairs: ${totalcost:,.2f}'),

print(f'The final value of boat: ${finalvalue:.2f}')

print('\nGoodbye')

I am trying to line up the results for the final 3 values. I am not sure if I should be using an f string, or alternatively "format(boatprice, '.2f')". I know the value and alignment should go between the colon and comma ${boatprice:HERE,.2f}'), I just cannot figure out how to put the values in so all three are in alignment. I've tried left, center, and right. I apologize for the basic question, I've just lost out on marks on three assignments already. Any help would be greatly appreciated!

Find elsewhere
🌐
Medium
shweta-lodha.medium.com › ways-to-align-text-strings-in-python-ef0f1dab5a28
Ways To Align Text Strings In Python | by Shweta Lodha | Medium
August 13, 2022 - Let’s have a look at those: For left-aligned text, you can use ljust(…) function, which stands for left justification. my_text = “Shift me.” · print(my_text.ljust(25) ) The above lines will display left-aligned text with a length of 25.
🌐
Note.nkmk.me
note.nkmk.me › home › python
Right-justify, Center, Left-justify Strings and Numbers in Python | note.nkmk.me
May 18, 2023 - Use the rjust(), center(), or ljust() methods to right-justify, center, or left-justify strings str in Python. You can convert numbers (int and float) to strings using str() and apply these methods. R ...
🌐
EyeHunts
tutorial.eyehunts.com › home › python print table align | example code
Python print table align | Example code - Tutorial - By EyeHunts
December 16, 2022 - Use format to print table aligns in Python. Using the .format approach, you could use padding to align all of your strings.
🌐
YouTube
youtube.com › watch
#67 Python for Beginners: Ways To Align Text In Python - YouTube
Blog: http://www.shwetalodha.in/Medium: https://medium.com/@shweta-lodhaJoin Medium membership at just $5/month :https://shweta-lodha.medium.com/membershipWa...
Published: August 13, 2022
🌐
TutorialsPoint
tutorialspoint.com › how-to-align-text-strings-using-python
How to Align Text Strings using Python?
# Format an invoice with proper ...--------------- Total $ 1100.49 · Python offers flexible text alignment through f-strings and string methods....
🌐
Stack Abuse
stackabuse.com › formatting-strings-with-python
Formatting Strings with Python
July 17, 2023 - You can align values within a specified length of text by using the <, >, or ^ symbols to specify left align, right align, or centering, respectively.
🌐
SQLPad
sqlpad.io › tutorial › python-formatted-output
Python formatted output | SQLPad
April 29, 2024 - Python provides several ways to align strings. Here are the most common ones: Left alignment uses < and ensures that the text is aligned to the left of the specified width. Right alignment uses > and aligns the text to the right.
🌐
w3resource
w3resource.com › python-exercises › string › python-data-type-string-exercise-37.php
Python: Display a number in left, right and center aligned of width 10 - w3resource
June 12, 2025 - print("Original Number: ", x) # Format and print the value of 'x' with left alignment, a width of 10 characters, and padding using spaces. print("Left aligned (width 10) :"+"{:< 10d}".format(x)) # Format and print the value of 'x' with right ...
Top answer
1 of 2
1

You can use String formatting using theFormat Specification Mini-Language.

For instance:

for i in range(len(entries)):
    print("{0:>6.2f}\t{1:>6.2f}\t{2:>6.2f}\t{3:>6.2f}".format(*entries[i]))

You get something like that:

Wind Speed  Old Formula New Formula Difference

  5.00    9.00    4.00    5.10
  6.00    5.00    2.00    2.80
  7.00    2.00    1.00    0.80
  8.00   -1.00    0.00   -1.10
  9.00   -3.00    0.00   -2.80
 10.00   -5.00   -1.00   -4.30
 11.00   -7.00   -2.00   -5.70

Or, using a more pythonic loop:

for entry in entries:
    print("{0:>6.2f}\t{1:>6.2f}\t{2:>6.2f}\t{3:>6.2f}".format(*entry))
2 of 2
0

You could just pad with spaces using str.format().

def draw_padded_string(s, width, align="left"):
    if align == "left":
        return "{s: <{width}}".format(s=s, width=width)
    elif align == "center":
        return s.center(width, ' ')
    elif align == "right":
        return "{s: >{width}}".format(s=s, width=width)

In this case, s is the string and width is the entire width of your column.

You would define this somewhere in your code, probably under your imports just to get it out of your way, but so long as it is defined before you start calling your print statements. This would change your print block a little, too:

width = 13

headers = ["Wind Speed", "Old Formula", "New Formula", "Difference"]
print_headers = []
for header in headers:
    print_headers.append(draw_padded_string(header, width))
print("".join(print_headers))
print()

for row in entries:
    print_row = []
    for data in row:
        print_row.append(draw_padded_string(data, width))
    print("".join(print_row))

What I did:

  • set width at 13 (your widest column right now is 11)
  • created lists of each row to be printed
  • applied our function to each item on the list
  • print the list as a single row using "".join(list)
  • changed from using your own integer tracking using i and j and instead let python iterate over your rows and columns for you

What you might want to do differently:

  • Use list comprehension to generate your lists (instead of for item in list
  • Adjust your column width based on the actual maximum list as below
column_length = max([len(word) for word in list_of_words])
🌐
Tutorial Reference
tutorialreference.com › python › examples › faq › python-how-to-align-output-in-printing
How to Align Output in Python Printings | Tutorial Reference
Aligning text in Python transforms raw data into professional, readable output. Use Basic Methods (ljust, center) for simple string manipulation or custom padding characters. Use f-string ({val:<10}) for most printing tasks, as they are concise and performant.
🌐
Educative
educative.io › answers › how-to-format-strings-in-python
How to format strings in Python
print("{0:4}, is the computer science portal for {1:10}!" ... By default, strings are left-aligned within the field, and numbers are right-aligned.