10
votes

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

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

     #
    #
   #
  #
 #
#

with code that looks similar to,

for i in range(6, 0, -1):
    print("{0:>i}".format("#"))
2
Just add parenthesis around the string being constructed: print(("{0:>"+str(i)+"}").format("#")) - niemmi
You can pass its value through format(): print("{0:>{1}}".format("#", i)) - Ashwini Chaudhary
@AshwiniChaudhary the # is fixed. So would it be possible to get it into the string instead of as a parameter? Like "{#:>{0}}".format(i), which doesn't work. - BlackShift

2 Answers

6
votes

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

Much simpler : instead of concatenating strings, you can use format again

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

Try it in idle:

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

     #
    #
   #
  #
 #
#

Or even fstring (as Florian Brucker suggested - I'm not an fstrings lover, but it would be incomplete to ignore them)

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

in idle :

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

     #
    #
   #
  #
 #
#