Python Forum

Full Version: How can I use 2 digits format for all the number?
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
How can I fix all the numbers to 2 digits format so that the numbers will be all aligned column wise in the rows below?

Thanks.
[attachment=1207]
In what? Console program? Spreadsheet? Web page?
(Aug-09-2021, 07:58 AM)deanhystad Wrote: [ -> ]In what? Console program? Spreadsheet? Web page?
Sorry, in Python.
number = 2
print(f'number is {number:02}')
Output:
number is 02
(Aug-09-2021, 08:42 AM)Yoriz Wrote: [ -> ]
number = 2
print(f'number is {number:02}')
Output:
number is 02
Thanks.

My apology for not being clear.

I meant from printing the numbers in lists within a list (sorry I do not know how to express that). Eg
[[1 2 3],[11 22 33],[1 32 6]] to be printed as

[[ 1 2 3], [ 11 22 33], [ 1 32 6]]

As format 3 digits (not 2 digits, realised I need a space in between the numbers).


Thanks.
(Aug-09-2021, 08:48 AM)plumberpy Wrote: [ -> ][[1 2 3],[11 22 33],[1 32 6]] to be printed as

[[ 1 2 3], [ 11 22 33], [ 1 32 6]]
list is a internal structure,when want display in output is common to take values of list and format it(without []).
lst = [[1, 2, 3], [11, 22, 33], [1, 32, 6]]
for inner in lst:
    print(' | '.join((f"{word:^2}" for word in inner)))
Output:
1 | 2 | 3 11 | 22 | 33 1 | 32 | 6
Tabulate can easily give fancier output.
from tabulate import tabulate

lst = [[1, 2, 3], [11, 22, 33], [1, 32, 6]]
print(tabulate(lst))
print(tabulate(lst, tablefmt="fancy_grid"))
print(tabulate(lst, tablefmt="github"))
Output:
-- -- -- 1 2 3 11 22 33 1 32 6 -- -- -- ╒════╤════╤════╕ │ 1 │ 2 │ 3 │ ├────┼────┼────┤ │ 11 │ 22 │ 33 │ ├────┼────┼────┤ │ 1 │ 32 │ 6 │ ╘════╧════╧════╛ |----|----|----| | 1 | 2 | 3 | | 11 | 22 | 33 | | 1 | 32 | 6 |
Beautiful!

I was also looking for the grids.

Many many thanks!