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 OverflowYou 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))
Seems like you might be looking for rjust:
https://docs.python.org/2/library/string.html#string.rjust
my_string = 'foo'
print my_string.rjust(10)
' foo'
The amount can be formated like this:
"${:.2f}".format(amount)
You can add padding to a string, for example for a width of 20:
"{:20s}".format(mystring)
You can right align the string, for example with a width of 7:
"{:>7s}".format(mystring)
Putting all this together:
s = "The subtotal was:"
a = 24.95
print("{:20s}{:>7s}".format(s, "${.2f}".format(a))
If you know the maximum sizes of the text and numbers, you can do
val_str = '${:.2f}'.format(val)
print('{:<18} {:>6}'.format(name+':', val_str))
It gets trickier if these aren't known in advance. Here's an approach, assuming names and values are lists:
value_format = '${:.2f}'.format
name_format = '{}:'.format
values_fmt = [value_format(val) for val in values]
names_fmt = [name_format(name) for name in names]
max_value_len = max(len(x) for x in values_fmt)
max_name_len = max(len(x) for x in names_fmt)
for name, val in zip(names_fmt, values_fmt):
print('{:<{namelen}} {:>{vallen}}'.format(name, val,
namelen=max_name_len, vallen=max_value_len))
There's no docstring. What does this code do? How do I call it? What does it return?
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
fullJustifymethod does not refer toself. So don't write a class, just write a function.Python strings have a
joinmethod 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:])Python strings have an
ljustmethod for left-justification within a fixed-width field. So this code:pad_spaces = maxWidth - len(oneline) oneline = oneline + " "*pad_spacescan be simplified to:
oneline = oneline.ljust(maxWidth)Python has a built-in function
divmodthat 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)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
doctestmodule.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 (usingyield).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
yieldeach 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)
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.
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])
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