string operations (ctrl characters)

Hans Nowak hnowak at
Thu Aug 16 10:44:48 CEST 2001

>===== Original Message From "DR" <dean at> =====

>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
        # 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.


--Hans Nowak

More information about the Python-list mailing list