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 theformat()
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!
Coders get paid six figures and more because they can solve problems more effectively using machine intelligence and automation.
To become more successful in coding, solve more real problems for real people. 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?
You build high-value coding skills by working on practical coding projects!
Do you want to stop learning with toy projects and focus on practical code projects that earn you money and solve real problems for people?
🚀 If your answer is YES!, consider becoming 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.
If you just want to learn about the freelancing opportunity, feel free to watch my free webinar “How to Build Your High-Income Skill Python” and learn how I grew my coding business online and how you can, too—from the comfort of your own home.