[Tutor] Removing control characters

Kent Johnson kent37 at tds.net
Thu Feb 19 21:36:07 CET 2009


On Thu, Feb 19, 2009 at 2:25 PM, Dinesh B Vadhia
<dineshbvadhia at hotmail.com> wrote:

> # 3) Replacing a set of characters with a single character ie.
>
> for c in str:
>     if c in set:
>         string.replace (c, r)
>
> to give
>
>> 'Chris Perkins : $$$-$$$$'
> My solution is:
>
> print ''.join[string.replace(c, r) for c in str if c in set]

With the syntax corrected this will not do what you want; the "if c in
set" filters the characters in the result, so the result will contain
only the replacement characters. You would need something like
''.join([ (r if c in set else c) for c in str])

Note that both 'set' and 'str' are built-in names and therefore poor
choices for variable names.

Kent


More information about the Tutor mailing list