Advan721
Advan721

Reputation: 55

How to place dots into the number with Python?

How can I automatically place dots by separating it with 3 digits in a group beginning from the right?

Example:

in: 1234; out 1.234
in: 12345678; out 12.345.678

Upvotes: 1

Views: 840

Answers (2)

Martijn Pieters
Martijn Pieters

Reputation: 1122092

You are looking for a thousands-separator. Format your number with the format() function to using commas as the thousands separator, then replace the commas with dots:

>>> format(1234, ',').replace(',', '.') 
'1.234'
>>> format(12345678, ',').replace(',', '.') 
'12.345.678'

Here the ',' format signals that the decimal number should be formatted with a thousands-separator (see the Format Specification Mini-language).

The same can be achieved in a wider string format with the str.format() method, where placeholders in the template are replaced with values:

>>> 'Some label for the value: {:,}'.format(1234).replace(',', '.')
'Some label for the value: 1,234'

but then you run the risk of accidentally replacing other full stops in the output string too!

Your other option would be to use the locale-dependent 'n' format, but that requires your machine to be configured for a locale that sets the right LC_NUMERIC options.

Upvotes: 9

user2555451
user2555451

Reputation:

Here is a simple solution:

>>> a = 12345678
>>> "{:,}".format(a)
'12,345,678'
>>> "{:,}".format(a).replace(",", ".")
'12.345.678'
>>>

This uses the .format method of a string to add the comma separators and then the .replace method to change those commas to periods.

Upvotes: 5

Related Questions