python format string thousand separator with spaces

PythonString Formatting

Python Problem Overview


For printing number with thousand separator, one can use the python format string :

'{:,}'.format(1234567890)

But how can I specify that I want a space for thousands separator?

Python Solutions


Solution 1 - Python

Here is bad but simple solution if you don't want to mess with locale:

'{:,}'.format(1234567890.001).replace(',', ' ')

Solution 2 - Python

Answer of @user136036 is quite good, but unfortunately it does not take into account reality of Python bugs. Full answer could be following:

Variant A

If locale of your platform is working right, then just use locale:

import locale
locale.setlocale(locale.LC_ALL, '')
print("{:,d}".format(7123001))

Result is dependent on your locale and Python implementation working right.

But what if Python formatting according to locale is broken, e.g. Python 3.5 on Linux?

Variant B

If Python does not respect grouping=True parameter, you can use locale and a workaround (use monetary format):

locale.setlocale(locale.LC_ALL, '')
locale._override_localeconv = {'mon_thousands_sep': '.'}
print(locale.format('%.2f', 12345.678, grouping=True, monetary=True))

Above gives 12.345,68 on my platform. Setting monetary to False or omitting it - Python does not group thousands. Specifying locale._override_localeconv = {'thousands_sep': '.'} do nothing.

Variant C

If you don't have time to check what is working OK and what is broken with Python on your platform, you can just use regular string replace function (if you want to swap commas and dot to dots and comma):

print("{:,.2f}".format(7123001.345).replace(",", "X").replace(".", ",").replace("X", "."))

Replacing comma for space is trivial (point is assumed decimal separator):

print("{:,.2f}".format(7123001.345).replace(",", " ")

Solution 3 - Python

This will set the locale environment to your default OS location:

import locale
locale.setlocale(locale.LC_ALL, '')

Then you can use:

"{0:n}".format(1234567890)

Solution 4 - Python

You'll have to use the 'n' locale-aware number format instead, and set your locale to one that uses a space as a thousands separator. Yes, this is painful.

> 'n' - Number. This is the same as 'd', except that it uses the current locale setting to insert the appropriate number separator characters.

Solution 5 - Python

Lets say you code:

print(f'{name} | Yearly salary: ${salary}.')

> PRINTS -> Kate | Yearly salary: $60000.

First put a , separator:

print(f'{name} | Yearly salary: ${salary:,}.')

> PRINTS -> Kate | Yearly salary: $60,000.

Then replace the comma with a space:

print(f'{name} | Yearly salary: {salary:,} USD.'.replace(',', ' '))

> PRINTS -> Kate | Yearly salary: 60 000 USD.

NB: Remember USD, $ or £, kroner etc. notation should match accordingly universal standards

Solution 6 - Python

Python community has it defined under PEP 378, where you can see that the main proposal includes format() function. So, by following that proposal, I suggest using the following:

format(1234567890, ',d').replace(',',' ')

Solution 7 - Python

If you don't want to use the local, a solution that works with every size of string :

    def format_number(string):
        j = len(string) % 3
        substrings = [string[3 * i + j:3 * (i + 1) + j] for i in                                         range(len(string)//3)]
        if j != 0:
            substrings.insert(0, string[:j])
        return " ".join(substrings)

Solution 8 - Python

You can use an f-string:

number = 1234567890
f"{number:,.2f}"

Attributions

All content for this solution is sourced from the original question on Stackoverflow.

The content on this page is licensed under the Attribution-ShareAlike 4.0 International (CC BY-SA 4.0) license.

Content TypeOriginal AuthorOriginal Content on Stackoverflow
QuestionwonzbakView Question on Stackoverflow
Solution 1 - PythonRazView Answer on Stackoverflow
Solution 2 - PythonstemdView Answer on Stackoverflow
Solution 3 - Pythonuser136036View Answer on Stackoverflow
Solution 4 - PythonMartijn PietersView Answer on Stackoverflow
Solution 5 - PythonPatrikView Answer on Stackoverflow
Solution 6 - Pythonad007View Answer on Stackoverflow
Solution 7 - PythonCaroline BeckerView Answer on Stackoverflow
Solution 8 - PythonAroldo PalaciosView Answer on Stackoverflow