How to Insert Commas into Numbers Using Python Regex – Quick Guide
This article explains how to format positive integer strings with thousand separators in Python by using a concise regular expression and the re.sub function, providing a clear code example and linking to the official documentation for further reference.
1. Introduction
In a recent Python community chat, a member asked how to format a positive integer string with thousand separators (e.g., 12345678 → 12,345,678) using regular expressions.
2. Implementation
The solution uses a regex that matches a digit followed by groups of three digits up to the end of the string: (\d)(?=(\d{3})+$) Applying re.sub inserts a comma after each matched digit:
import re
num_str = "12345678"
formatted_num_str = re.sub(r'(\d)(?=(\d{3})+$)', r'\1,', num_str)
print(formatted_num_str) # Output: 12,345,678For more details, refer to Python’s official re documentation.
3. Conclusion
The article demonstrates a concise regex‑based method to add thousand separators to numeric strings in Python, helping readers solve similar formatting problems.
Signed-in readers can open the original source through BestHub's protected redirect.
This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactand we will review it promptly.
Python Crawling & Data Mining
Life's short, I code in Python. This channel shares Python web crawling, data mining, analysis, processing, visualization, automated testing, DevOps, big data, AI, cloud computing, machine learning tools, resources, news, technical articles, tutorial videos and learning materials. Join us!
How this landed with the community
Was this worth your time?
0 Comments
Thoughtful readers leave field notes, pushback, and hard-won operational detail here.
