Fundamentals 4 min read

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.

Python Crawling & Data Mining
Python Crawling & Data Mining
Python Crawling & Data Mining
How to Insert Commas into Numbers Using Python Regex – Quick Guide

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,678

For 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.

Original Source

Signed-in readers can open the original source through BestHub's protected redirect.

Sign in to view source
Republication Notice

This article has been distilled and summarized from source material, then republished for learning and reference. If you believe it infringes your rights, please contactadmin@besthub.devand we will review it promptly.

Pythonprogramming fundamentalsregexrestring formatting
Python Crawling & Data Mining
Written by

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!

0 followers
Reader feedback

How this landed with the community

Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.