0
Just use the method format
of string:
>>> '{:>13,.2f}'.format(100000)
' 100,000.00'
Where:
- The keys,
{}
, define a group referring to the parameters offormat
; - The two points,
:
, initialize the value formatting rules; - The biggest sign,
>
, sets the right alignment; - The number 13,
13
same, sets the total output space; - The comma,
,
, represents the thousands separator character; - The point,
.
, starts the decimal part formatting rules; - The number 2,
2
even, defines that there will be only 2 decimal places; - The letter f,
f
, defines that the input will be a type float;
Read it then, {:>13,.2f}
how: format this number float with 2 decimal places, using the comma as the thousands separator, aligned to the right in a space of 13 characters.
Assuming you own each line in a list, you could do:
>>> linha = [1, 100000.00, 9282.21, 8333.33, 948.88, 91666.67]
>>> print('{:^6} {:>13,.2f} {:>9,.2f} {:>11,.2f} {:>9,.2f} {:>11,.2f}'.format(*linha))
' 1 100,000.00 9,282.21 8,333.33 948.88 91,666.67'
By following the reasoning, with few additions to the above code, you easily produce the output:
--------------------------------------------------------------------------
Número Saldo Inicial Prestação Amortização Juros Saldo Final
------ ------------- --------- ----------- --------- -----------
1 100,000.00 9,282.21 8,333.33 948.88 91,666.67
1 100,000.00 9,282.21 8,333.33 948.88 91,666.67
1 100,000.00 9,282.21 8,333.33 948.88 91,666.67
1 100,000.00 9,282.21 8,333.33 948.88 91,666.67
1 100,000.00 9,282.21 8,333.33 948.88 91,666.67
--------------------------------------------------------------------------
In versions 3.6+ of Python there are calls f-strings that facilitate this data formatting. The rules are the same, but instead of using the method format
, you enter the name of the variables in the formatting itself, thus making the code more readable. The name f-string is due to the prefix f
which must exist next to the string:
>>> linha = [1, 100000.00, 9282.21, 8333.33, 948.88, 91666.67]
>>> numero, saldo_inicial, prestacao, amortizacao, juros, saldo_final = linha
>>> print(f'{numero:^6} {saldo_inicial:>13,.2f} {prestacao:>9,.2f} {amortizacao:>11,.2f} {juros:>9,.2f} {saldo_final:>11,.2f}')
' 1 100,000.00 9,282.21 8,333.33 948.88 91,666.67'
And finally, as monetary data, do not discard the option to format via locale
:
>>> import locale
>>> locale.setlocale(locale.LC_ALL, 'pt_BR')
>>> locale.format('%.2f', 100000.00, grouping=True)
'100.000,00'
See also locale.currency
.
Other readings:
And how are you doing? What was the output obtained?
– Woss
I print one below the other.
– Sandson Costa
Number: Values. Balance values etc... Then I want to print one next to the other as in the image.
– Sandson Costa
Show the code
– Leandro Angelo
You can use this python library (Pretty Table), there is an introduction to it: https://www.vooo.pro/insights/python-pretty-table/
– Erick Santos