Compress a string

Arnaud Delobelle arnodel at googlemail.com
Sun May 18 14:44:56 EDT 2008


"Matt Porter" <mabbikeel at gmail.com> writes:

> Hi guys,
>
> I'm trying to compress a string.
> E.g:
>  "AAAABBBC" -> "ABC"
>
> The code I have so far feels like it could be made clearer and more
> succinct, but a solution is currently escaping me.
>
>
> def compress_str(str):
>     new_str = ""
>     for i, c in enumerate(str):
>         try:
>             if c != str[i+1]:
>                 new_str += c
>         except IndexError:
>             new_str += c
>     return new_str
>
>
> Cheers
> Matt
> -- 
> --

>>> string = 'sssssssssspppppppaaaaaaam'
>>> ''.join(x for x, y in zip(string, '\0'+string) if x != y)
'spam'

HTH

PS: I keep seeing problems on this list whose solution seems to
involve 'window' iterating over a sequence. E.g.

>>> list(window('eggs', 2))
[('e', 'g'), ('g', 'g'), ('g', 's')]

-- 
Arnaud



More information about the Python-list mailing list