Cleaning up a string

MRAB google at mrabarnett.plus.com
Thu Jul 26 02:10:20 CEST 2007


On Jul 24, 8:47 pm, James Stroud <jstr... at mbi.ucla.edu> wrote:
> Hello all,
>
> I dashed off the following function to clean a string in a little
>
> program I wrote:
>
> def cleanup(astr, changes):
>    for f,t in changes:
>      atr = astr.replace(f, t)
>    return astr
>
> where changes would be a tuple, for example:
>
> changes = (
>               ('%', '\%'),
>               ('$', '\$'),
>               ('-', '_')
>            )
>
> If these were were single replacements (like the last), string.translate
> would be the way to go. As it is, however, the above seems fairly
> inefficient as it potentially creates a new string at each round. Does
> some function or library exist for these types of transformations that
> works more like string.translate or is the above the best one can hope
> to do without writing some C? I'm guessing that "if s in astr" type
> optimizations are already done in the replace() method, so that is not
> really what I'm getting after.
>
A simple way of replacing single characters would be this:

def cleanup(astr, changes):
    changes = dict(changes)
    return "".join(changes.get(c, c) for c in astr)




More information about the Python-list mailing list