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
Solution 1:
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 inrange(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 inrange(6, 0, -1):
print(f"{'#':>{i}}")
in idle :
>>> for i inrange(6, 0, -1): print(f"{'#':>{i}}")
######
Solution 2:
Currently your code interpreted as below:
for i inrange(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 ================
######
>>>
Post a Comment for "Format In Python By Variable Length"