Splitting a string into substrings of equal size

candide candide at free.invalid
Fri Aug 14 20:22:57 EDT 2009


Suppose you need to split a string into substrings of a given size (except
possibly the last substring). I make the hypothesis the first slice is at the
end of the string.
A typical example is provided by formatting a decimal string with thousands
separator.


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)

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

outputting :

75096042068045 -->  75,096,042,068,045
509 -->  509
12024 -->  12,024
7 -->  7
2009 -->  2,009


Thanks



More information about the Python-list mailing list