18

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:

     #
    #
   #
  #
 #
#
4
  • 1
    Just add parenthesis around the string being constructed: print(("{0:>"+str(i)+"}").format("#")) Commented May 1, 2016 at 4:22
  • 2
    You can pass its value through format(): print("{0:>{1}}".format("#", i)) Commented May 1, 2016 at 4:22
  • @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. Commented Jul 28, 2017 at 10:32
  • Near-duplicate: How can I fill out a Python string with spaces? Commented Jan 9, 2024 at 3:06

2 Answers 2

20

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:

     #
    #
   #
  #
 #
#
Sign up to request clarification or add additional context in comments.

1 Comment

This obviously also works with f-strings: x = '#'; y = 3; z = f'{x:>{y}}'
7

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

1 Comment

Yep, the '}'.format is the same as the typical some_object.method.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.