4

I already saw a lot of question teaching how easy is to do it with comma as thousands separator:

>>> format(1123000,',d')
'1,123,000'

But if I try to use a dot, it goes nuts:

>>> format(1123000,'.d')
ValueError: Format specifier missing precision

Is there a simple Python built-in locale independent way to make it output '1.123.000' instead of '1,123,000'?

I already found this answer on Add 'decimal-mark' thousands separators to a number but it manually do it. Can it be simpler as format(1123000,'.d') and locale independent? Or Python does not provide it built-in?

@Eugene Yarmash Using itertools can give you some more flexibility:

>>> from itertools import zip_longest
>>> num = "1000000"
>>> sep = "."
>>> places = 3
>>> args = [iter(num[::-1])] * places
>>> sep.join("".join(x) for x in zip_longest(*args, fillvalue=""))[::-1]
'1.000.000'
Evandro Coan
  • 8,560
  • 11
  • 83
  • 144

1 Answers1

11

If you are only dealing with integers, you can use:

x = 123456789
'{:,}'.format(x).replace(',','.')
# returns
'123.456.789'
James
  • 32,991
  • 4
  • 47
  • 70
  • 2
    realyyyy??????? I solved my problem using django's humanize (https://stackoverflow.com/questions/346467/format-numbers-in-django-templates), but this solution sounds really strange... – Alan Tygel Apr 10 '19 at 20:33