Search code examples
pythonstringprintingformat

Format in python by variable length


I want to print a staircase-like pattern. I tried this using .format() method:

for i in range(6, 0, -1):
    print("{0:>"+str(i)+"}".format("#"))

But it gave me following error:

ValueError: Single '}' encountered in format string

Basically the idea is to print this output:

     #
    #
   #
  #
 #
#

Solution

  • Currently your code interpreted as below:

    for i in range(6, 0, -1):
        print ( ("{0:>"+str(i))     +     ("}".format("#")))
    

    So the format string is constructed of a single "}" and that's not correct. You need the following:

    for i in range(6, 0, -1):
        print(("{0:>"+str(i)+"}").format("#"))
    

    Works as you want:

    ================ RESTART: C:/Users/Desktop/TES.py ================
         #
        #
       #
      #
     #
    #
    >>>