Couple functions I need, assuming they exist?

George Sakkis gsakkis at rutgers.edu
Mon Jun 20 12:01:30 EDT 2005


> I assume you mean translating something like '1000000' to '1,000,000'?
> I don't know of an existing function that does this, but here's a
> relatively simple implementation:
>
> py> import itertools as it
> py> def add_commas(s):
> ...     rev_chars = it.chain(s[::-1], it.repeat('', 2))
> ...     return ','.join(''.join(three_digits)
> ...                     for three_digits
> ...                     in it.izip(*[rev_chars]*3))[::-1]
> ...

Or for an equivalent less cryptic (IMHO) recipe:

def num2str(num):
    '''Return a string representation of a number with the thousands
    being delimited.

    >>> num2str(65837)
    '65,837'
    >>> num2str(6582942)
    '6,582,942'
    >>> num2str(23)
    '23'
    >>> num2str(-1934)
    '-1,934'
    '''
    parts = []
    div = abs(num)
    while True:
        div,mod = divmod(div,1000)
        parts.append(mod)
        if not div:
            if num < 0: parts[-1] *= -1
            return ','.join(str(part) for part in reversed(parts))


Regards,
George




More information about the Python-list mailing list