string operations (ctrl characters)

Hans Nowak hnowak at cuci.nl
Thu Aug 16 04:44:48 EDT 2001


>===== Original Message From "DR" <dean at valtronics.co.za> =====

>So all I'm left with is [ and . I tried to do the same for those
>characters, but I can't seem to get rid of them.
>
>        test15 = string.replace(test14,"\\",'')
>        test16 = string.replace(test15,"[[" ,'')
>
>The above attempts didn't work.
>
>If anyone could offer any advice or suggest a better way of doing this, it
>would be great.  Is there a better way of doing this ??

There are several approaches to this. I'm no regex expert, but I figure there 
should be a way to dream up a regular expression that removes, or replaces, 
characters with a certain value.

You don't *need* regexen for this, though. One approach could be, scanning the 
string for "acceptable" characters, and replacing anything else with some 
default character, or removing it.

Some untested sample code:

ALLOWED = "abcdefghijklmnopqrstuvwxyz"
# etc... The allowed characters.

newstring = ""
for c in weirdstring:
    if c in ALLOWED:
        newstring += c
    else:
        # do nothing if you want to remove unwanted characters, or add
        # something like ' newstring += " " ' for replacing, etc.

I don't know if speed is an issue... this could be slow(ish)... although 
there's probably room for optimization.

HTH,

--Hans Nowak





More information about the Python-list mailing list