Right Justify python

前端 未结 5 1866
失恋的感觉
失恋的感觉 2021-01-19 13:39

how can I justify the output of this code?

N = int(input())
case = \'#\'
print(case)

for i in range(N):
    case += \'#\'
    print(case)
相关标签:
5条回答
  • 2021-01-19 13:41
    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.

    0 讨论(0)
  • 2021-01-19 13:41

    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 ##########
    
    0 讨论(0)
  • 2021-01-19 13:46

    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.

    0 讨论(0)
  • 2021-01-19 13:48

    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'
    
    0 讨论(0)
  • 2021-01-19 13:55

    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))
    
    0 讨论(0)
提交回复
热议问题