For some reason, I always forget how to do this. Tired of that. Let's blog about it so it sticks.

To format a number with thousand-commas you do:


>>> n = 1234567
>>> f"{n:,}"
'1,234,567'

To add whitespace to a string you do:


>>> name="peter"
>>> f"{name:<20}"
'peter               '

How to combine these in one expression, you do:


>>> n = 1234567
>>> f"{n:<15,}"
'1,234,567      '

Comments

Sarma Akondi

NIce 👌

Your email will never ever be published.

Previous:
Leibniz formula for π in Python, JavaScript, and Ruby March 14, 2024 Python, JavaScript
Next:
Search GitHub issues by title, only May 31, 2024 GitHub
Related by category:
How I run standalone Python in 2025 January 14, 2025 Python
get in JavaScript is the same as property in Python February 13, 2025 Python
How to resolve a git conflict in poetry.lock February 7, 2020 Python
Best practice with retries with requests April 19, 2017 Python
Related by keyword:
How to pad/fill a string by a variable in Python using f-strings January 24, 2020 Python
Format thousands in Python February 1, 2019 Python
Credit Card formatter in Javascript November 19, 2013 JavaScript
Format numbers with numberWithCommas() or Number.toLocaleString() March 5, 2019 Web development, JavaScript