Skip to content
Advertisement

Python – Print at a given position from the left of the screen

The following code:

i1, i2, i3 = 1234, 45, 856
print(f"{i1:<5}{i2:<5}{i3}")

displays:

1234 45   856

This is fine but what I’d like to do is to display each integer at a given position from the left of the screen.

If possible, I also would like to keep using f string, not C-style formatting please.

This would allow me to easilly print something nicely aligned like:

 (1234)   (45)    (856)
 (12)     (45744) (844456)

Adding parenthesis like this with f-string is possible of course but it is a little nightmare. It would be much easier to provide the hardcoded position on the line where to print

BTW, using integers is just an example, I wish the solution worked for any type (float, boolean, arrays…).

Advertisement

Answer

I eventually found a workaround which consists in using encapsulated f strings:

i1, i2, i3 = 1234, 45, 856
print(f'{f"({i1})":<10}{f"({i2})":<10}{f"({i3})":<10}')
i1, i2, i3 = 12, 454, 8564
print(f'{f"({i1})":<10}{f"({i2})":<10}{f"({i3})":<10}')

output:

(1234)    (45)      (856)     
(12)      (454)     (8564)   
User contributions licensed under: CC BY-SA
8 People found this is helpful
Advertisement