Adding commas into number string

Featured Image

Adding commas to an integer string in Python involves formatting the numerical data to improve its readability and presentation. Python offers various built-in functions and modules to add commas to integer strings, such as the format() function, the locale module, and regular expressions.

These tools allow developers to format integer strings in different ways based on their specific needs, making it easier for users to interpret and comprehend the numerical data.

Quick Introduction

Developers can utilize the format() function to format a string by placing placeholders that are replaced with corresponding values. To illustrate, using the thousands separator specifier, an integer can be formatted with commas.

In addition to the format() function, the locale module is another useful tool for formatting integers based on a user’s system preferences, including the symbols for thousands separators and decimal points.

An alternative method of adding commas to integer strings is by using regular expressions. This enables developers to match and replace complex patterns in the string. In this method, the re.sub() function is utilized to search and substitute parts of the string that match a specified regular expression pattern.

How to Add Commas to Number Strings in Python

Let’s now look at the different ways you can add commas to number string outputs without changing the original data type.

Method 1: Basic implementation

{:,}.format() will add commas to the digits after every thousand place.

num = 2232890
print("The Number: ", num)
print("Result : {:,}".format(num))

Output:

The Number:  2232890
Result : 2,232,890

Method 2: Using format specifier.

,d in (format(num,',d')) is a format specifier which will convert a number to a string of decimal digit.

num = 2232890
print("The Number: ", num)
result = (format(num,',d'))
print('Result : ',result)

Output:

The Number:  2232890
Result :  2,232,890

Method 3: Rounding off

To round the float format number with commas as thousands separators we use {:,.2f}. The digits beyond two places after the decimal get ignored. If we want to round the number to 3 places, we can do it by replacing 2 with 3.

num = 2232890.82728
print("The Number: ", num)
print("Result : {:,.2f}".format(num))

Output:

The Number:  2232890.82728
Result : 2,232,890.83

Method 4: Using re.sub

import re
num = 2232890

print("The original number is : " + str(num))

res = re.sub(r'(\d{2})(?=\d)', r'\1,', str(num)[::-1])[::-1]

print("The number after inserting commas : " + str(res))

Output:

The original number is : 2232890
The number after inserting commas : 2,23,28,90

This line of code utilizes the re.sub() function from the Python re module to execute a search and replace of a regular expression on a string named num.

The regular expression, r'(\d{2})(?=\d)', seeks any two digits that are followed immediately by another digit, forming a three-digit sequence. The (\d{2}) component of the regular expression establishes a capturing group that matches the first two digits, and the (?=\d) portion is a lookahead assertion that necessitates the following character to be a digit but does not include it in the match.

The replacement string, r'\1,', substitutes the three-digit sequence with the first two digits followed by a comma. The \1 serves as a backreference to the first capturing group in the regular expression, which in this instance is the two digits that were matched. The comma is added to distinguish the first two digits from the next digit.

To enable the regular expression to match the digits from right to left instead of from left to right, the integer num is converted to a string using str(num)[::-1], and the order of the characters in the string is then reversed.

The re.sub() function then performs the substitution on the reversed string, and the result is also reversed using [::-1] to restore the original order of the characters. The final outcome is stored in a variable named res.

Conclusion

Adding commas to an integer string in Python is a straightforward process that can significantly improve the readability and usability of numerical data. In Python, several built-in methods can be used to achieve this goal, such as the format() function and the locale module.

These methods can format numbers according to the user’s preferences and system settings, making the resulting output more user-friendly. More complex formatting requirements can be met by using regular expressions to add commas to integer strings.

We hope this article answered your questions about how to add commas to numbers in Python.

Recommendation