How to change thousands separator to apostrophe in format string

Viewed 824

The following prints a decimal number with commas as thousands separator:

num = 123456789
print(f"{num:,}")

123,456,789

According to PEP-378 (which seems relevant here?), the separator can be a comma, dot, space, apostrophe or underscore. I managed to get an underscore:

print(f"{num:_}")

123_456_789

But how do I get a dot, space, or most importantly to me, an apostrophe?

2 Answers

the easy way to do this will be to store your string in a variable like string and assuming you want apostrophes instead of underscores use,

print(string.replace('_',"'"))

The "proper" way to do this is using the locale module:

>>> import locale
>>> locale.setlocale(locale.LC_NUMERIC, 'de_CH.utf8')
>>> locale.format_string('%d', 123457890, grouping=True)
"123'457'890"

In this case this requires the swiss-german locale to be installed on your system, but it is compatible with all installed locales, such that you can easily generate pretty much all formats that are used somewhere.

Related