QA Graphic

Commify in Python

Easily add commas to numbers

Back when I was doing a lot of Perl programing, commify was the function that I used to add commas to numbers.

Here's a sample code:


#######################################################
# Comma Formating
# This area is where the FORMATING will be done to change the
# variable from ######.####### to #,###.##
#######################################################
sub commify {
    local($_) = shift;
    1 while s/^(-?d+)(d{3})/$1,$2/;
    return $_;
}

Python Style

In Python, you don't need a function to add commas to numbers.


#!/usr/bin/env /usr/bin/python3
# Using format() function
x = 124908120
print('{:,}'.format(x))
# f-strings (Python 3.9 and later)
# With f-strings, you can directly include the :, 
# inside the curly braces to format the number with commas.
y12948129
y_format=f"{y:,}"
print(y_format)

 

Comments

Add Comments

Name:
Comment: