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: The first print statement ... 15 spaces, filling the remaining space with *. The third line right-aligns "Python" within 15 spaces, filling the left side with =....
Discussions

How do I right-justify strings with dollar signs and percentages?
"Formatting doesn't seem to do literally anything at all." Well, all of Python's number formatting methods allow you to restrict the output to two decimal places and to right justify it. I suggest that you post your code so that people here can advise you what is going wrong with it. You can edit your original post to include it. Guide to posting code in this subreddit: https://www.reddit.com/r/learnpython/wiki/faq#wiki_how_do_i_format_code.3F More on reddit.com
🌐 r/learnpython
8
3
February 13, 2022
How to align text with formatting?
Put two tabs between the line item description and the money value, like this: print(f'\nInitial purchase price: \t\t${boatprice:,.2f}') More on reddit.com
🌐 r/learnpython
2
2
February 8, 2022
f-string alignment
It works for me, mate. Maybe your computer is broken. >>> print(f"{'today':25}" + "xx") today xx >>> print(f"{'tomorrow':25}" + "xx") tomorrow xx >>> print(f"{'the day after tomorrow':25}" + "xx") the day after tomorrow xx Actually, looking at it a bit it's pretty clear that your browser is not using a monospace font. More on reddit.com
🌐 r/learnpython
6
1
April 29, 2023
Why doesn't my code align, when using escape characters?
The general rule is to not rely on tab stops for formatting. Specifically, tab should take you to the next tab stop, but, if your text is long enough, the next tab stop is different for "Employee" than it is for "Fran". You could try using longer names for Fran, Bob, and Joe just to confirm this, but I suggest you use spaces and column alignment or Python's text formatting features instead of tabs. More on reddit.com
🌐 r/learnpython
6
2
April 20, 2023
🌐
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.
🌐
LabEx
labex.io › tutorials › python-how-to-align-output-in-python-printing-418802
How to align output in Python printing | LabEx
The script you just created demonstrates three basic string alignment methods in Python: ljust(width): Left-justifies the string within a field of the specified width. rjust(width): Right-justifies the string within a field of the specified width.
🌐
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. ... After formatting the alignment of output text ...
🌐
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. Then you follow those symbols with a character width you desire. Python > 2.6: >>> left_aligned = "Left Align" >>> center = "Centered" >>> ...
🌐
Scientifically Sound
scientificallysound.org › 2016 › 10 › 17 › python-print3
Take control of your Python print() statements: part 3 | Scientifically Sound
November 17, 2021 - The last thing we need to learn ... how we want to align our text or numbers in these spaces. We can left-adjust (<), right-adjust (>) ......
Find elsewhere
🌐
TutorialsPoint
tutorialspoint.com › how-to-align-text-strings-using-python
How to Align Text Strings using Python?
# Right align with 30 character width text = "Right Aligned String!" print(f"{text:>30}") print(f"{'Hello':>20}World")
🌐
Scaler
scaler.com › home › topics › python › string formatting in python
String Formatting in Python - Scaler Topics
June 11, 2024 - ... For the alignment of strings, ... Here n is the total length of the required output string. ... To right align a string, we use the “:>n” symbol inside the placeholder....
🌐
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, '•'))
🌐
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 ...
🌐
LabEx
labex.io › tutorials › python-how-to-manipulate-python-string-alignment-419448
How to manipulate Python string alignment | LabEx
At LabEx, we recommend practicing string alignment techniques to enhance your Python text processing skills. text = "Hello" left_aligned = text.ljust(10) print(f"'{left_aligned}'") ## Output: 'Hello ' text = "World" right_aligned = text.rjust(10) print(f"'{right_aligned}'") ## Output: ' World' text = "Python" centered = text.center(10) print(f"'{centered}'") ## Output: ' Python ' text = "LabEx" custom_left = text.ljust(10, '-') custom_right = text.rjust(10, '*') print(f"'{custom_left}', '{custom_right}'") ## Left alignment print("{:<10}".format("Left")) ## Right alignment print("{:>10}".format
🌐
SQLPad
sqlpad.io › tutorial › python-formatted-output
Python formatted output | SQLPad
April 29, 2024 - Right alignment uses > and aligns the text to the right. Center alignment uses ^ and centers the text within the given width. # Left align with a width of 20 characters left_aligned = "{:<20}".format("left") print(f"'{left_aligned}'") # Right ...
🌐
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 - ... The above lines will display left-aligned text with a length of 25. The alternate way of doing this is by using format(…) function as shown below: ... For right-aligned text, you can use rjust(…) function, which stands for right ...
🌐
Educative
educative.io › answers › how-to-format-strings-in-python
How to format strings in Python
The padding will start at 4. It ... is the computer science portal for {1:10}!" ... By default, strings are left-aligned within the field, and numbers are right-aligned....
🌐
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!

🌐
GeeksforGeeks
geeksforgeeks.org › python-string-ljust-rjust-center
Python String - ljust(), rjust(), center() - GeeksforGeeks
January 2, 2025 - It returns an array with the elements of arr right-justified in a string of length width.It fills remaining space of each array element using fillchr parameter.If fillchr is not passed t ... String alignment in Python helps make text look neat and organized, especially when printing data of different lengths.
🌐
USAVPS
usavps.com › home › python › python tutorial: how to right align numbers in python?
Python Tutorial: How to Right Align Numbers in Python? - USAVPS
October 22, 2024 - You can also use the :> specifier for right alignment: number = 42 formatted_number = f"{number:>5}" print(formatted_number) # Output: " 42" F-strings are not only easier to read but also more efficient than the previous methods. When dealing with multiple numbers, you can use loops to format and align them in a structured manner.
🌐
Vultr Docs
docs.vultr.com › python › standard-library › str › rjust
Python str rjust() - Right-Justify String | Vultr Docs
December 31, 2024 - headers = ["ID", "Name", "Age"] ... right, ensuring all elements are vertically aligned and properly formatted. The str.rjust() method in Python simplifies the process of aligning text to the right, a common requirement for ...