Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3.5 string format: How to add a thousands-separator and also right justify?

How would I get a string that is equal to:

'    100,000.23'

Given that I have the variable

num = 100000.23

I can right justify with:

num = 100000.23
'{:>10.2f}'.format(num)

and I can thousands separate with:

num = 100000.23
'{:,}'.format(num)

But how can I do both at the same time?

like image 720
user1367204 Avatar asked Sep 10 '18 20:09

user1367204


1 Answers

Combine the two by adding a comma following the alignment instruction:

>>> '{:>12,.2f}'.format(num)
'  100,000.23'

Explanation
For reference: Format Specification Mini-language

{:       >      12         ,               .2         f      }
        ^^^     ^^        ^^^              ^^^       ^^^
       align   width  grouping_option   precision   type
like image 162
user3483203 Avatar answered Oct 26 '22 05:10

user3483203