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

Question:

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…).

Asked By: u2gilles

||

Answers:

You may need to design your own formatting tool. Let’s say the field for i3 starts at start. Prepare the string of the first two fields, trim or extend it, as needed, and append the string for the third item:

s12 = f"{i1:<5}{i2:<5}"
start = 8

(s12[:start] if start <= len(s) else s + " " * (start - len(s))) + f"{i3}"
#'1234 45 856'
start=12
(s12[:start] if start <= len(s) else s + " " * (start - len(s))) + f"{i3}"
#'1234 45     856'
Answered By: DYZ

Not sure why do you need this but you can try this:

>>> i1, i2, i3 = 1234, 45, 856
>>> print(f"{i1:<5}{i2:<5} {i3}") # your example
1234 45    856 
>>> print(f"{i1:<5}{i2:<5} r{i3}") # start from the begging and overwrite
8564 45
>>> print(f"{i3:>50}r {i1:<5}{i2:<5}")
1234 45                                       856

The third case moves i3 50 chars to the right and only then prints i1 and i2. But be careful it becomes a little bit tricky to print everything in the correct way.

If you want to format your output as columns look at this Create nice column output in python or some kind of terminal counter/progress bar Text Progress Bar in the Console [closed]

Answered By: alberand

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)   
Answered By: u2gilles

huikhux

jsakbksbkssc ksckas
dflnjfldfoelfjlsfjojejf’ljfeofejjfje’ofjeojfeljasojfej
iewjfojoejf’
iofjfojef joejofjew joiedjfoejfoijoni oij ojoej;fjf:I:OJIOJ;eLFnojwlfnjjw;e

  1. j e;ojfel leff*e
  2. w*jifeow;
  3. ieoiewwiifolwji fiwe
  4. oijiewjjiwjiojfowjjoieoiooj oijoei
    eeekhouehohfoehf ewiiwiihwiudendnhfui55inlgnihdk
Answered By: assdsdxsdxs
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.