Splitting a string into substrings of equal size

Gregor Lingl gregor.lingl at aon.at
Sat Aug 15 20:49:45 CEST 2009


> 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



More information about the Python-list mailing list