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 giv
Solution 1:
I eventually found a workaround which consists in using encapsulated f strings:
i1, i2, i3 = 1234, 45, 856print(f'{f"({i1})":<10}{f"({i2})":<10}{f"({i3})":<10}')
i1, i2, i3 = 12, 454, 8564print(f'{f"({i1})":<10}{f"({i2})":<10}{f"({i3})":<10}')
output:
(1234) (45) (856)
(12) (454) (8564)
Solution 2:
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'
Solution 3:
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]
Post a Comment for "Python - Print At A Given Position From The Left Of The Screen"