Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Print a big integer with punctions with Python3 string formatting mini-language

I want a point after each three digits in a big number (e.g. 4.100.200.300).

>>> x = 4100200300
>>> print('{}'.format(x))
4100200300

This question is specific to Pythons string formatting mini-language.

like image 490
buhtz Avatar asked Nov 29 '15 11:11

buhtz


People also ask

What is %d in Python3?

The %d operator is used as a placeholder to specify integer values, decimals, or numbers. It allows us to print numbers within strings or other values. The %d operator is put where the integer is to be specified. Floating-point numbers are converted automatically to decimal values. Python3.

What is %s %i in Python?

%s specifically is used to perform concatenation of strings together. It allows us to format a value inside a string.

What is %d and %i in Python?

Here's what python.org has to say about %i: Signed integer decimal. And %d: Signed integer decimal. %d stands for decimal and %i for integer.


1 Answers

There's only one available thousands separator.

The ',' option signals the use of a comma for a thousands separator.

(docs)

Example:

'{:,}'.format(x) # 4,100,200,300

If you need to use a dot as a thousand separator, consider replacing commas with '.' or setting the locale (LC_NUMERIC category) appropriately.

You could use this list to find the right locale. Note that you'll have to use the n integer presentation type for locale-aware formatting:

import locale
locale.setlocale(locale.LC_NUMERIC, 'de_DE') # or da_DK, or lt_LT, or mn_MN, or ...
'{:n}'.format(x) # 4.100.200.300

In my opinion, the former approach is much simpler:

'{:,}'.format(x).replace(',', '.') # 4.100.200.300

or

format(x, ',').replace(',', '.') # 4.100.200.300
like image 176
vaultah Avatar answered Sep 30 '22 07:09

vaultah