Thousands separators for numbers in Python < 2.6


Python 2.7 and later have format(), but in Python 2.6 and lower, if you want to format big numbers with thousands separators, you are on your own. This code seem to work nicely and is tolerant.

# ---------------------------------------------------------------------------------------
def format_nr(number):
# 1000000000 --> 1'000'000'000
# Python 2.7 has formats, but we are still under 2.6
# ---------------------------------------------------------------------------------------

    try:
        number = int(number)        
        s = '%d' % number
        groups = []
        while s and s[-1].isdigit():
            groups.append(s[-3:])
            s = s[:-3]
        return s + "'".join(reversed(groups))

    except:
        return number

print format_nr(1000000000)
1’000’000’000

The quote separator is common in Europe. US usually wants comma.