Splitting a string into substrings of equal size

Jan Kaliszewski zuo at chopin.edu.pl
Sat Aug 15 15:38:53 CEST 2009


Dnia 15-08-2009 o 08:08:14 Rascal <jonrascal at gmail.com> wrote:

> I'm bored for posting this, but here it is:
>
> def add_commas(str):
>     str_list = list(str)
>     str_len = len(str)
>     for i in range(3, str_len, 3):
>         str_list.insert(str_len - i, ',')
>     return ''.join(str_list)

For short strings (for sure most common case) it's ok: simple and clear.
But for huge ones, it's better not to materialize additional list for the
string -- then pure-iterator-sollutions would be better (like Gabriel's or
mine).

Cheers,
*j

-- 
Jan Kaliszewski (zuo) <zuo at chopin.edu.pl>



More information about the Python-list mailing list