Skip to content
geeksforgeeks
  • Courses
    • DSA to Development
    • Get IBM Certification
    • Newly Launched!
      • Master Django Framework
      • Become AWS Certified
    • For Working Professionals
      • Interview 101: DSA & System Design
      • Data Science Training Program
      • JAVA Backend Development (Live)
      • DevOps Engineering (LIVE)
      • Data Structures & Algorithms in Python
    • For Students
      • Placement Preparation Course
      • Data Science (Live)
      • Data Structure & Algorithm-Self Paced (C++/JAVA)
      • Master Competitive Programming (Live)
      • Full Stack Development with React & Node JS (Live)
    • Full Stack Development
    • Data Science Program
    • All Courses
  • Tutorials
    • Data Structures & Algorithms
    • ML & Data Science
    • Interview Corner
    • Programming Languages
    • Web Development
    • CS Subjects
    • DevOps And Linux
    • School Learning
  • Practice
    • Build your AI Agent
    • GfG 160
    • Problem of the Day
    • Practice Coding Problems
    • GfG SDE Sheet
  • Contests
    • Accenture Hackathon (Ending Soon!)
    • GfG Weekly [Rated Contest]
    • Job-A-Thon Hiring Challenge
    • All Contests and Events
  • Python Tutorial
  • Interview Questions
  • Python Quiz
  • Python Glossary
  • Python Projects
  • Practice Python
  • Data Science With Python
  • Python Web Dev
  • DSA with Python
  • Python OOPs
Open In App
Next Article:
Python - Add List Items
Next article icon

Add Comma Between Numbers - Python

Last Updated : 17 Jan, 2025
Comments
Improve
Suggest changes
Like Article
Like
Report

When working with large numbers in Python, adding commas for better readability can make them easier to understand. In this article, we’ll explore simple ways to add commas between numbers, helping make large numbers more readable and neatly formatted.

Using format()

format() function in Python provides a simple and efficient way to add commas between numbers.

Python
n = 1000000   res = "{:,}".format(n) print(res)  

Output
1,000,000 

Explanation:

  • format() function is used to format the number and add commas.
  • The :, within the curly braces tells Python to insert commas as a thousand separator.

Let's explore some more ways and see how we can add commas between numbers.

Table of Content

  • Using f-strings
  • Using the locale module
  • Using str.replace() with a loop
  • Using re.sub()

Using f-strings

f-strings provide an even more convenient way to add commas to numbers. This method provides a quick way to format numbers.

Python
n = 1000000 res = f"{n:,}" print(res) 

Output
1,000,000 

Explanation:

  • f-strings allow us to embed expressions directly inside string literals.
  • The :, is used to format the number with commas as a thousand separator.
  • This method is more readable and concise compared to using str.format()

Using locale module

locale module allows us to format numbers according to the conventions of a specific locale. This is useful if we need to format numbers in a way that’s specific to certain countries or regions.

Python
import locale  # Setting the locale to 'en_US' for formatting numbers with commas (US-style) locale.setlocale(locale.LC_ALL, "en_US") n = 1000000  # Using the locale module to format the number with commas as thousand separators res = locale.format_string("%d", n, grouping=True) print(res)   

Explanation:

  • setlocale() function sets the locale for formatting numbers.
  • format_string function is used to format the number with commas based on the locale.
  • This method is ideal when dealing with international number formatting requirements.

Using str.replace() with a loop

Another approach is to manually insert commas using str.replace() and a loop. This method can still be used for smaller tasks or custom implementations.

Python
n = 1000000  n_str = str(n)  # Converting the number to a string res = ""  # Initializing an empty string to store the formatted result count = 0  # Initializing a counter to track the number of digits processed  # Iterating through the digits of the number in reverse order for digit in reversed(n_str):     res = digit + res  # Adding the current digit to the result string     count += 1       # Adding a comma after every 3 digits, except at the end of the number     if count % 3 == 0 and count != len(n_str):         res = "," + res  # Inserting a comma before the current result  print(res) 

Output
1,000,000 

Explanation:

  • This method involves manually looping through the digits of the number and inserting commas after every third digit.
  • While functional, it requires more code and is less efficient compared to using built-in methods like format() or f-strings.

Using re.sub()

re.sub() function from Python’s regular expressions module can also be used to insert commas into a number string. This method allows more control over how the commas are inserted but is more complex than the built-in methods.

Python
import re   n = 1000000   # The regular expression adds a comma after every group of three digits, starting from the right res = re.sub(r"(?<=\d)(?=(\d{3})+(?!\d))", ",", str(n)) print(res)  

Output
1,000,000 

Explanation:

  • re.sub() function uses a regular expression to match positions in the string where commas need to be inserted.
  • This method is powerful for complex formatting tasks but is not as efficient or readable as format() or f-strings.

Next Article
Python - Add List Items
author
manjeet_04
Improve
Article Tags :
  • Python
  • Python Programs
  • Python string-programs
Practice Tags :
  • python

Similar Reads

  • How to Add Two Numbers in Python
    The task of adding two numbers in Python involves taking two input values and computing their sum using various techniques . For example, if a = 5 and b = 7 then after addition, the result will be 12. Using the "+" Operator+ operator is the simplest and most direct way to add two numbers . It perfor
    5 min read
  • Python Program to add two hexadecimal numbers
    Given two hexadecimal numbers, write a Python program to compute their sum. Examples: Input: a = "01B", b = "378" Output: 393 Explanation: B (11 in decimal) + 8 = 19 (13 in hex), hence addition bit = 3, carry = 1 1 + 7 + 1 (carry) = 9, hence addition bit = 9, carry = 0 0 + 3 + 0 (carry) = 3, hence a
    6 min read
  • Python - Add space between Numbers and Alphabets in String
    In this article, we delve into a practical Python solution to improve text readability by adding spaces between numbers and alphabets in strings by utilizing Python's powerful string manipulation capabilities. Input: test_str = 'ge3eks4geeks is1for10geeks' Output: ge 3 eks 4 geeks is 1 for 10 geeks
    9 min read
  • Python program to add two binary numbers
    Given two binary numbers, write a Python program to compute their sum. Examples: Input: a = "11", b = "1" Output: "100" Input: a = "1101", b = "100" Output: 10001Approach: Naive Approach: The idea is to start from the last characters of two strings and compute digit sum one by one. If the sum become
    4 min read
  • Python - Add List Items
    Python lists are dynamic, which means we can add items to them anytime. In this guide, we'll look at some common ways to add single or multiple items to a list using built-in methods and operators with simple examples: Add a Single Item Using append()append() method adds one item to the end of the l
    3 min read
  • Print Numbers in an Interval - Python
    In this article, we are going to learn how to print numbers within a given interval in Python using simple loops, list comprehensions, and step-based ranges. For Example: Input : i = 2, j = 5Output : 2 3 4 5 Input : i = 10, j = 20 , s = 2Output : 10 12 14 16 18 20 Let’s explore different methods to
    2 min read
  • How to Add Numbers in a Csv File Using Python
    When working with CSV files in Python, adding numbers in the CSV file is a common requirement. This article will guide you through the process of adding numbers within a CSV file. Whether you're new to data analysis or an experienced practitioner, understanding this skill is vital for efficient data
    3 min read
  • Python List Add/Append Programs
    This article covers a wide range of methods for adding elements to a list, including: Basic addition techniques like append(), extend(), and insert().Appending multiple items, lists, tuples, dictionaries and objects.Performing list modifications such as adding at the beginning, middle or end.Advance
    3 min read
  • Python | Alternate character addition
    Sometimes, while working with Python, we can have a problem in which we need to add a character after every character in String. This kind of problem can have its application in many day-day programming domains. Lets discuss certain ways in which this task can be performed. Method #1 : Using loop Th
    5 min read
  • Insert a number in string - Python
    We are given a string and a number, and our task is to insert the number into the string. This can be useful when generating dynamic messages, formatting output, or constructing data strings. For example, if we have a number like 42 and a string like "The number is", then the output will be "The num
    2 min read
geeksforgeeks-footer-logo
Corporate & Communications Address:
A-143, 7th Floor, Sovereign Corporate Tower, Sector- 136, Noida, Uttar Pradesh (201305)
Registered Address:
K 061, Tower K, Gulshan Vivante Apartment, Sector 137, Noida, Gautam Buddh Nagar, Uttar Pradesh, 201305
GFG App on Play Store GFG App on App Store
Advertise with us
  • Company
  • About Us
  • Legal
  • Privacy Policy
  • In Media
  • Contact Us
  • Advertise with us
  • GFG Corporate Solution
  • Placement Training Program
  • Languages
  • Python
  • Java
  • C++
  • PHP
  • GoLang
  • SQL
  • R Language
  • Android Tutorial
  • Tutorials Archive
  • DSA
  • Data Structures
  • Algorithms
  • DSA for Beginners
  • Basic DSA Problems
  • DSA Roadmap
  • Top 100 DSA Interview Problems
  • DSA Roadmap by Sandeep Jain
  • All Cheat Sheets
  • Data Science & ML
  • Data Science With Python
  • Data Science For Beginner
  • Machine Learning
  • ML Maths
  • Data Visualisation
  • Pandas
  • NumPy
  • NLP
  • Deep Learning
  • Web Technologies
  • HTML
  • CSS
  • JavaScript
  • TypeScript
  • ReactJS
  • NextJS
  • Bootstrap
  • Web Design
  • Python Tutorial
  • Python Programming Examples
  • Python Projects
  • Python Tkinter
  • Python Web Scraping
  • OpenCV Tutorial
  • Python Interview Question
  • Django
  • Computer Science
  • Operating Systems
  • Computer Network
  • Database Management System
  • Software Engineering
  • Digital Logic Design
  • Engineering Maths
  • Software Development
  • Software Testing
  • DevOps
  • Git
  • Linux
  • AWS
  • Docker
  • Kubernetes
  • Azure
  • GCP
  • DevOps Roadmap
  • System Design
  • High Level Design
  • Low Level Design
  • UML Diagrams
  • Interview Guide
  • Design Patterns
  • OOAD
  • System Design Bootcamp
  • Interview Questions
  • Inteview Preparation
  • Competitive Programming
  • Top DS or Algo for CP
  • Company-Wise Recruitment Process
  • Company-Wise Preparation
  • Aptitude Preparation
  • Puzzles
  • School Subjects
  • Mathematics
  • Physics
  • Chemistry
  • Biology
  • Social Science
  • English Grammar
  • Commerce
  • World GK
  • GeeksforGeeks Videos
  • DSA
  • Python
  • Java
  • C++
  • Web Development
  • Data Science
  • CS Subjects
@GeeksforGeeks, Sanchhaya Education Private Limited, All rights reserved
We use cookies to ensure you have the best browsing experience on our website. By using our site, you acknowledge that you have read and understood our Cookie Policy & Privacy Policy
Lightbox
Improvement
Suggest Changes
Help us improve. Share your suggestions to enhance the article. Contribute your expertise and make a difference in the GeeksforGeeks portal.
geeksforgeeks-suggest-icon
Create Improvement
Enhance the article with your expertise. Contribute to the GeeksforGeeks community and help create better learning resources for all.
geeksforgeeks-improvement-icon
Suggest Changes
min 4 words, max Words Limit:1000

Thank You!

Your suggestions are valuable to us.

What kind of Experience do you want to share?

Interview Experiences
Admission Experiences
Career Journeys
Work Experiences
Campus Experiences
Competitive Exam Experiences