Python | Add comma between numbers
Sometimes, while working with currencies, we need to put commas between numbers to represent a currency, hence given a string, we can have a problem to insert commas into them. Let’s discuss certain ways in which this task can be performed.
Method #1 : Using str.format()
The string format function can be used by supplying the valid formatter to perform the formatting. The string formatter is called with the value as argument to perform this particular task.
# Python3 code to demonstrate working of # Adding comma between numbers # Using str.format() # initializing number test_num = 1234567 # printing original number print("The original number is : " + str(test_num)) # Using str.format() # Adding comma between numbers res = ('{:, }'.format(test_num)) # printing result print("The number after inserting commas : " + str(res)) |
The original number is : 1234567 The number after inserting commas : 1, 234, 567
Method #2 : Using format()
This task can also be performed without taking the help of format library of strings but the normal format library that can use the “d” notation of numbers and simply insert the commas where required.
# Python3 code to demonstrate working of # Adding comma between numbers # Using format() # initializing number test_num = 1234567 # printing original number print("The original number is : " + str(test_num)) # Using format() # Adding comma between numbers res = (format (test_num, ', d')) # printing result print("The number after inserting commas : " + str(res)) |
The original number is : 1234567 The number after inserting commas : 1, 234, 567
Recommended Posts:
- Python | Convert key-value pair comma separated string into dictionary
- Python program to add two numbers
- Python | N consecutive Odd or Even Numbers
- Random Numbers in Python
- Python Program for Fibonacci numbers
- Complex Numbers in Python | Set 1 (Introduction)
- Python | Extract numbers from string
- Python Numbers | choice() function
- Python | Numbers in a list within a given range
- Python | Check whether string contains only numbers or not
- Python Program for GCD of more than two (or array) numbers
- Python | Indices of numbers greater than K
- Python | Largest number possible from list of given numbers
- Python | Print all string combination from given numbers
- Python program to print even numbers in a list
If you like GeeksforGeeks and would like to contribute, you can also write an article using contribute.geeksforgeeks.org or mail your article to contribute@geeksforgeeks.org. See your article appearing on the GeeksforGeeks main page and help other Geeks.
Please Improve this article if you find anything incorrect by clicking on the "Improve Article" button below.



