Friday, March 4, 2011

Adding commas to integer strings for readability

There ase many ways to make more human readable the string representation of an integer.
Click on Activestate.com thousands separator

As an example, 1234567890 looks more humanly readable as 1,234,567,890.

We normally use other people's tested and understood code to save time, but this is one good programming problem.

The manual way to do this is to insert commas before blocks of contiguous three digits.
Strings are supposed to be immutable in Python by design for simplicity. Every changes to a string must be done by a copy. So we convert a string to a list just so to insert characters!


def  withcommas(s):
     p = len(s) -3
     s = list(s)
     while p > 0:
        s.insert(p, ",")
        p -= 3
     return "".join(s)



But suppose that s starts with a '+" or "-" sign? Then the leftmost position for a comma is at the second character or index 1. We add a conditional test so that the code will not be put off by the leading sign.

def  withcommas(s):
     p = len(s) -3
     s = list(s)
     if s.startswith("+") or s.startswith("-"):
        firstpos = 1
     while p > firstpos:
        s.insert(p, ",")
        p -= 3
     return "".join(s)

and finally we include a trivial programming problem for the reader. Instead of 3, let the caller of withcommas() specify a blocklength to the function. We are just getting ready for the time when we will concentrate on creating mathematical tables.

Our aim is to create simple, working first prototypes. The reader again is encouraged to read and search the cited reference above for faster solutions.

1 comment:

  1. Oh my goodness. Not to sound disrespectful but looking at this just turned my headache to a full blown migraine. But I still love you! Tsup!

    ReplyDelete