redwood_gm
redwood_gm

Reputation: 353

How can I print numbers in python with thin space characters as the thousands separators?

I know for example "{:,}".format(123456789) will print '123,456,789' as output in python.

However, instead of the commas I would like the thin space character as the thousands separator. According to here, the python source encoding for the thin space character is u"\u2009".

So I tried replacing the comma in "{:,}" by u"\u2009", but that results in a syntax error. This might be because python can't deal with the resulting nested double quotes and something needs to be escaped.

So is there a way to make this, or some other mechanism work? And by the way I'd like to suppress the single quotes that appear in the output as well.

Upvotes: 4

Views: 2317

Answers (2)

picnix_
picnix_

Reputation: 377

You can use replace method from str to replace , by thin spaces after having formatted it, i.e: "{:,}".format(123456789).replace(",", u"\u2009")

According to the official documentation here, only , and _ can be used as separators. To use a user-defined one, you need to use the n representation, and change your locale settings (see https://docs.python.org/3/library/locale.html#locale.LC_NUMERIC). You can create a new localization and use this fake localization for what you want but this is a rather complicated solution.

EDIT: By a fake localization, I really mean a new locale in your computer, not in Python. You can read https://askubuntu.com/questions/653008/how-to-create-a-new-system-locale for more details (I think this can be adapterd on most distributions)

Upvotes: 6

cs95
cs95

Reputation: 402814

I can offer you an obvious workaround:

>>> n = 123456789
>>> print(f'{n:,}'.replace(',', u'\u2009'))
123 456 789

Works for str.format the same way.

Upvotes: 3

Related Questions