What is the pythonic way to do this ?


For my part, i reach to this rather complicated code:


# ----------------------

def comaSep(z,k=3, sep=','):
    z=z[::-1]
    x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1]
    return sep.join(x)

# Test
for z in ["75096042068045", "509", "12024", "7", "2009"]:
    print z+" --> ", comaSep(z)


Just if you are interested, a recursive solution:

>>> def comaSep(z,k=3,sep=","):
        return comaSep(z[:-3],k,sep)+sep+z[-3:] if len(z)>3 else z

>>> comaSep("7")
'7'
>>> comaSep("2007")
'2,007'
>>> comaSep("12024")
'12,024'
>>> comaSep("509")
'509'
>>> comaSep("75096042068045")
'75,096,042,068,045'
>>>

Gregor
--
http://mail.python.org/mailman/listinfo/python-list

Reply via email to