Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Format in python by variable length

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("#"))
like image 262
Jay Patel Avatar asked May 01 '16 04:05

Jay Patel


1 Answers

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

     #
    #
   #
  #
 #
#
like image 141
Camion Avatar answered Sep 27 '22 22:09

Camion