Jay Patel
Jay Patel

Reputation: 560

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:

     #
    #
   #
  #
 #
#

Upvotes: 18

Views: 20062

Answers (2)

Camion
Camion

Reputation: 1374

Use f-strings

for i in range(6, 0, -1): 
    print(f"{'#':>{i}}")

or:

Use format() (instead of concatenating strings)

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

Both solutions give the output:

     #
    #
   #
  #
 #
#

Upvotes: 18

EbraHim
EbraHim

Reputation: 2349

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 ================
     #
    #
   #
  #
 #
#
>>> 

Upvotes: 7

Related Questions