<br><br><div class="gmail_quote">On Sat, Aug 15, 2009 at 4:06 PM, MRAB <span dir="ltr"><<a href="mailto:python@mrabarnett.plus.com">python@mrabarnett.plus.com</a>></span> wrote:<br><blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">

<div><div></div><div class="h5">ryles wrote:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
On Aug 14, 8:22 pm, candide <cand...@free.invalid> wrote:<br>
<blockquote class="gmail_quote" style="border-left: 1px solid rgb(204, 204, 204); margin: 0pt 0pt 0pt 0.8ex; padding-left: 1ex;">
Suppose you need to split a string into substrings of a given size (except<br>
possibly the last substring). I make the hypothesis the first slice is at the<br>
end of the string.<br>
A typical example is provided by formatting a decimal string with thousands<br>
separator.<br>
<br>
What is the pythonic way to do this ?<br>
<br>
For my part, i reach to this rather complicated code:<br>
<br>
# ----------------------<br>
<br>
def comaSep(z,k=3, sep=','):<br>
    z=z[::-1]<br>
    x=[z[k*i:k*(i+1)][::-1] for i in range(1+(len(z)-1)/k)][::-1]<br>
    return sep.join(x)<br>
<br>
# Test<br>
for z in ["75096042068045", "509", "12024", "7", "2009"]:<br>
    print z+" --> ", comaSep(z)<br>
<br>
# ----------------------<br>
<br>
outputting :<br>
<br>
75096042068045 -->  75,096,042,068,045<br>
509 -->  509<br>
12024 -->  12,024<br>
7 -->  7<br>
2009 -->  2,009<br>
<br>
Thanks<br>
</blockquote>
<br>
py> s='1234567'<br>
py> ','.join(_[::-1] for _ in re.findall('.{1,3}',s[::-1])[::-1])<br>
'1,234,567'<br>
py> # j/k ;)<br>
</blockquote>
<br></div></div>
If you're going to use re, then:<div class="im"><br>
<br>
>>> for z in ["75096042068045", "509", "12024", "7", "2009"]:<br></div>
        print re.sub(r"(?<=.)(?=(?:...)+$)", ",", z)<div class="im"><br>
<br>
        <br>
75,096,042,068,045<br>
509<br></div>
12,024<br>
7<br>
2,009<div><div></div><div class="h5"></div></div></blockquote><div><br>Can you please break down this regex? <br></div></div><br>