How to Print an Integer with Commas as Thousands Separators in Python?

Problem Formulation: Given an integer number. How to convert the integer to a string representation for printing or other use that has thousand separators?

Example:

  • Given an integer number 1000000.
  • You want the string representation '1,000,000'.

Method 1: f-Strings

Using the modern f-strings is, in my opinion, the most Pythonic solution to add commas as thousand-separators for all Python versions above 3.6: f'{1000000:,}'. The inner part within the curly brackets :, says to format the number and use commas as thousand separators.

>>> f'{1000000:,}'
'1,000,000'

Method 2: string.format()

>>> '{:,}'.format(1000000)
'1,000,000'

You use the format specification language expression '{:,}' to convert the integer number 1000000 to a string with commas as thousand separators.

  • The outer part, the curly brackets '{...}' says to use the number passed into the format() function as a basis of the formatting process.
  • The inner part within the curly brackets :, says to format the number and use commas as thousand separators.

Method 3: string.format() + string.replace() to Obtain Points as Thousand Separators

If you use points as a thousand-separator—for example in 1.000.000 as done in Europe—you can replace the commas in the comma-separated number using the suffix .replace(',', '.') in '{:,}'.format(x).replace(',','.') for any integer number x.

>>> '{:,}'.format(1000000).replace(',','.')
'1.000.000'

A similar approach can be done with f-strings:

>>> f'{1000000:,}'.replace(',','.')
'1.000.000'

Method 4: format()

An alternative way to add commas as thousand separators is to use the ',d' formatting syntax in the format() function.

>>> format(1000000, ',d')
'1,000,000'

Source: https://stackoverflow.com/questions/1823058/how-to-print-number-with-commas-as-thousands-separators

Where to Go From Here?

Enough theory, let’s get some practice!

To become successful in coding, you need to get out there and solve real problems for real people. That’s how you can become a six-figure earner easily. And that’s how you polish the skills you really need in practice. After all, what’s the use of learning theory that nobody ever needs?

Practice projects is how you sharpen your saw in coding!

Do you want to become a code master by focusing on practical code projects that actually earn you money and solve problems for people?

Then become a Python freelance developer! It’s the best way of approaching the task of improving your Python skills—even if you are a complete beginner.

Join my free webinar “How to Build Your High-Income Skill Python” and watch how I grew my coding business online and how you can, too—from the comfort of your own home.

Join the free webinar now!