How to Add Commas to Numbers in Python
To add commas to numbers in Python, you can use different methods.
The following examples show how to add commas to numbers in Python using different ways.
Using format() Function
We can use the format() function to add commas to a number.
Suppose we have the following number:
# Declare number
number = 1000000
# Print number
print("Number:", number)
# Add commas to a number using format() function
formatted_number = '{:,}'.format(number)
# Show formatted number
print("Formatted number with commas:", formatted_number)
Output: 👇️
Number: 1000000
Formatted number with commas: 1,000,000
In this example, we use the format() function to add commas to the number.
Using f-strings
We can use f-strings to add commas to a number.
Suppose we have the same number as above.
We can use the following code to add commas to the number:
# Add commas to a number using f-strings
formatted_number = f'{number:,}'
# Show formatted number
print("Formatted number with commas:", formatted_number)
Output: 👇️
Number: 1000000
Formatted number with commas: 1,000,000
In this example, we use f-strings to add commas to the number.
Using Locale Module
Python’s locale module provides a way to format numbers based on the user’s locale. The locale module supports different locales, and it’s useful when dealing with internationalization. Here’s an example:
# Import locale library
import locale
# Declare number
number = 1000000
# Print number
print("Number:", number)
# Add commas to a number using locale module
locale.setlocale(locale.LC_ALL, 'en_US.UTF-8')
formatted_number = locale.format_string("%d", number, grouping=True)
# Show formatted string
print("Formatted number with commas:", formatted_number)
Output: 👇️
Number: 1000000
Formatted number with commas: 1,000,000
In this example, we imported the locale module and set it to use the ’en_US.UTF-8’ locale. Then, we used the format_string() method to format the number with commas.