You can use format with > to right justify

N = 10
for i in range(1, N+1):
    print('{:>10}'.format('#'*i))

Output

         #
        ##
       ###
      ####
     #####
    ######
   #######
  ########
 #########
##########

You can programattically figure out how far to right-justify using rjust as well.

for i in range(1, N+1):
    print(('#'*i).rjust(N))
Answer from Cory Kramer on Stack Overflow
🌐
Note.nkmk.me
note.nkmk.me › home › python
Right-justify, Center, Left-justify Strings and Numbers in Python | note.nkmk.me
May 18, 2023 - Format strings and numbers with format() in Python · To right-justify, center, or left-justify, use [CHARACTER][DIRECTION][STRING_LENGTH] as the format string.
🌐
Vultr Docs
docs.vultr.com › python › standard-library › str › rjust
Python str rjust() - Right-Justify String | Vultr Docs
December 31, 2024 - The str.rjust() method in Python is a built-in String method used for right-justifying string data. This function is typically used to align text to the right side of a specified width by padding it on the left with a specified fill character ...
🌐
W3Schools
w3schools.com › python › ref_string_rjust.asp
Python String rjust() Method
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training · ❮ String Methods · Return a 20 characters long, right justified version of the word "banana": txt = "banana" x = txt.rjust(20) print(x, "is my favorite fruit.") Try it Yourself » ·
🌐
Tutorialspoint
tutorialspoint.com › python › string_rjust.htm
Python String rjust() Method
When we pass the total string length as width and letters as the fillchar parameter, the method returns the justified string to its right
🌐
Medium
medium.com › @remisharoon › mastering-text-justification-with-python-a-detailed-guide-to-leetcode-problem-68-cab95de3142
Mastering Text Justification with Python: A Detailed Guide to LeetCode Problem 68 | by Remis Haroon | Medium
July 26, 2023 - Today, we’re taking a deep dive into a common algorithmic challenge you might encounter in a coding interview or competitive programming competition. This problem, known as Text Justification or LeetCode Problem 68, requires not only knowledge of Python programming but also a clear understanding of strings and formatting rules.
Find elsewhere
🌐
Learning About Electronics
learningaboutelectronics.com › Articles › How-to-justify-text-in-Python.php
How to Justify Text in Python
So to left justify text, we use the ljust() function. This function takes 2 parameters. The first is how many characters in total are in the string. So, realize that this is not how many characters there are of the character you chose to use during the justifying.
Top answer
1 of 2
8
  1. There's no docstring. What does this code do? How do I call it? What does it return?

  2. A class represents a group of persistent objects with common behaviour. But there are no persistent objects here, so there is no need for a class. This is also apparent from the fact that the fullJustify method does not refer to self. So don't write a class, just write a function.

  3. Python strings have a join method for concatenation. So this code:

    oneline = ""
    for ind in range(start_ind, num_of_words-1):
        oneline = oneline + words[ind] + " "
    oneline = oneline + words[num_of_words-1]
    

    can be simplified to:

    oneline = ' '.join(words[start_ind:])
    
  4. Python strings have an ljust method for left-justification within a fixed-width field. So this code:

    pad_spaces = maxWidth - len(oneline)
    oneline = oneline + " "*pad_spaces
    

    can be simplified to:

    oneline = oneline.ljust(maxWidth)
    
  5. Python has a built-in function divmod that simultaneously computes the quotient and remainder. So this code:

    basic_pad_spaces = extra_spaces // (word_num - 1)
    addition_pad_spaces = extra_spaces % (word_num - 1)
    

    can be simplied to:

    basic_pad_spaces, addition_pad_spaces = divmod(extra_spaces, word_num - 1)
    
  6. Left justification has to be done in two cases: a single word on a line, and the last line. It would therefore make sense to extract this common code into a function:

    def left_justify(words, width):
        """Given an iterable of words, return a string consisting of the words
        left-justified in a line of the given width.
    
        >>> left_justify(["hello", "world"], 16)
        'hello world     '
    
        """
        return ' '.join(words).ljust(width)
    

    Even though this is a simple one-line implementation, giving it a name improves the readability of the code where it is called. Note also the example in the docstring: this can be run and checked using the doctest module.

  7. When you are writing code that takes an input sequence (here, some words) and produces an output sequence (here, the justified lines), then it's a good idea in Python to write the code so that it iterates over the input (using for), and generates the output (using yield).

    With this approach: there's no need to keep the whole input and output sequences in memory at once (you operate on one or a few items at a time); there's no need to remember indexes into the input sequence (you just process each item as you get it); and there's no need to accumulate and return the output sequence (you just yield each item as you compute it).

    In this case:

    def justify(words, width):
        """Divide words (an iterable of strings) into lines of the given
        width, and generate them. The lines are fully justified, except
        for the last line, and lines with a single word, which are
        left-justified.
    
        >>> words = "This is an example of text justification.".split()
        >>> list(justify(words, 16))
        ['This    is    an', 'example  of text', 'justification.  ']
    
        """
        line = []             # List of words in current line.
        col = 0               # Starting column of next word added to line.
        for word in words:
            if line and col + len(word) > width:
                if len(line) == 1:
                    yield left_justify(line, width)
                else:
                    # After n + 1 spaces are placed between each pair of
                    # words, there are r spaces left over; these result in
                    # wider spaces at the left.
                    n, r = divmod(width - col + 1, len(line) - 1)
                    narrow = ' ' * (n + 1)
                    if r == 0:
                        yield narrow.join(line)
                    else:
                        wide = ' ' * (n + 2)
                        yield wide.join(line[:r] + [narrow.join(line[r:])])
                line, col = [], 0
            line.append(word)
            col += len(word) + 1
        if line:
            yield left_justify(line, width)
    
2 of 2
1

Why on Earth are you storing fullJustify as a function in the class Solution? In fact, the class solution serves no purpose whatsoever. It can be removed.

Secondly, function names and variable names should be in the style snake_case, not camelCase. Classes should be in PascalCase.

The three comments above the function Solution.fullJustify, should be stored in a docstring. Here's how you could convert those comments.

def full_justify(words, max_width):
    """
    words     - string[]
    max_width - integer
    returns  - string[]
    """
    ...

This line can be shortened from len_of_line = len_of_line + len(words[runner]) to len_of_line += len(words[runner]). There are other places you could do this. This syntax also supports other operators, like *, or /.

Finally, I find it to be clearer to declare variables on separate lines. For example, the line len_of_line, word_num_line = 0, 0 would become two separate lines, len_of_line = 0, and word_num_line = 0.

🌐
GeeksforGeeks
geeksforgeeks.org › python-string-ljust-rjust-center
Python String - ljust(), rjust(), center() - GeeksforGeeks
January 2, 2025 - The return type of ljust() is a new string that is left-justified with padding.
🌐
YouTube
youtube.com › watch
Left Justify And Right Justify A String With ljust() rjust() | Python Tutorial - YouTube
How to left justify and right just a string in Python using the ljust() and rjust() string methods which create a new left justified or right justified strin...
Published: February 21, 2023
🌐
Rip Tutorial
riptutorial.com › justify strings
Python Language Tutorial => Justify strings
Python provides functions for justifying strings, enabling text padding to make aligning various strings much easier.
🌐
Toppr
toppr.com › guides › python-guide › references › methods-and-functions › methods › string › rjust › python-string-rjust
Python rjust() function | Why do we use Python String rjust() function? |
September 27, 2021 - Python rjust() is a built-in function that returns a right-justified string according to the width specified and fills the remaining spaces with blank spaces if the character argument is not passed.
🌐
W3Schools
w3schools.com › python › ref_string_ljust.asp
Python String ljust() Method
Python Examples Python Compiler Python Exercises Python Quiz Python Challenges Python Practice Problems Python Server Python Syllabus Python Study Plan Python Interview Q&A Python Training · ❮ String Methods · Return a 20 characters long, left justified version of the word "banana": txt = "banana" x = txt.ljust(20) print(x, "is my favorite fruit.") Try it Yourself » ·
🌐
Delft Stack
delftstack.com › home › howto › python › right justify string in python
How to Right Justify String in Python | Delft Stack
February 20, 2025 - Due to this, the program runs into a TypeError exception saying that it expects an integer input and not a string. To avoid this error, we can use f-strings to right justify the strings.
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