Python 3 Nesting String format

Viewed 3620

I'm trying to generate a simple triangle shape with numbers, where the output might look like this:

  1
 22
333

However, I can't get this to work with a nested String format, the best I can achieve is the following...

        for i in range(1, size+1):    
            line = f'{i}' *i
            print(f"{line:>{size}}")

Ideally, I'd like to have 'line' nested within the print method. Any suggestions?

2 Answers

Actually if what you want is to embed the "line" creation within the f-string itself, you can achieve it with:

for i in range(1, size+1):
    print(f"{str(i) * i:>{size}}")

Alternatively you can also form a string with the old % operator, in there, if needed.

for i in range(1, size+1):
    print(f"{'%s' % (i) * i:>{size}}")
Related