how can I justify the output of this code?
N = int(input())
case = \'#\'
print(case)
for i in range(N):
case += \'#\'
print(case)
N = int(input())
for i in range(N+1):
print(" "*(N-i) + "#"*(i+1))
Print the right number of spaces followed by the right number of the "#" characters.
One liner using f-string and join:
print("\n".join([f"{'#' * i:>10}" for i in range(1, 11)]))
Output:
#
##
###
####
#####
######
#######
########
#########
##########
If you would like to include row number you can do following:
print("\n".join([f"{i:<3}{'#' * i:>10}" for i in range(1, 11)]))
Output:
1 #
2 ##
3 ###
4 ####
5 #####
6 ######
7 #######
8 ########
9 #########
10 ##########
The string.format()
method has this as part of its syntax.
print "{:>10}".format(case)
The number in the string tells python how many characters long the string should be, even if it's larger than the length of case
. And the greater than sign tells it to right justify case
within that space.
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'
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))