[jcd at sdf.lonestar.org: Re: Compress a string]

J. Clifford Dyer jcd at sdf.lonestar.org
Sun May 18 14:13:57 EDT 2008


On Sun, May 18, 2008 at 07:06:10PM +0100, Matt Porter wrote regarding Compress a string:
> 
> 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

def compress_str(s): 
    # str is a builtin keyword. Don't overload it.
	out = []
	for c in s:
		if out and c == out[-1]:
			out.append(c) # This is faster than new_str += c
	return ''.join(out) 





More information about the Python-list mailing list