Format in python by variable length

11,285

Solution 1

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

Solution 2

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}}")

     #
    #
   #
  #
 #
#
Share:
11,285
Jay Patel
Author by

Jay Patel

Hello World! (But obviously that had to be my first few words.) I'm a student currently pursuing my B.Tech degree in Computer Engineering field from CHARUSAT, India. I'm into programming since 2014 and mostly as the title says I'm a Python Enthusiast. I love working with Python, and experiment on stuff with it. I choose Machine Learning through Pattern Recognition as my domain. World is a beautiful place, and Programming makes it even more wonderful !

Updated on June 05, 2022

Comments

  • Jay Patel
    Jay Patel almost 2 years

    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("#"))
    
  • Kevin J. Chase
    Kevin J. Chase about 8 years
    Yep, the '}'.format is the same as the typical some_object.method.
  • Florian Brucker
    Florian Brucker almost 4 years
    This obviously also works with f-strings: x = '#'; y = 3; z = f'{x:>{y}}'