Formatting a numerical string w/commas

Wm. King wjk at wjk.mv.com
Thu Feb 24 00:54:35 EST 2000


As a relative newbie - I thought about what you wanted to do
to insert a comma in a string containing numbers -----------
and came up with the following - the regular expression and other
stuff I am doing could probably be tightened up I guess cause I don't
know all the in's and out's yet but I think its kinda interesting:

import re
pattern=re.compile("[0-9][0-9][0-9][0-9][\.\,$]")

test=123567789.98
teststr=str(test)
a = pattern.search(teststr)
while a:
 b = a.regs[0]
 c = b[0] + 1
 teststr = teststr[0:c] + "," + teststr[c:]
 a = pattern.search(teststr)

Would like to know what anyone else thinks about
one - thanks




More information about the Python-list mailing list