Removing Control characters

Hans Nowak wurmy at earthlink.net
Thu Jan 2 09:58:30 EST 2003


Amol Sonaikar wrote:

> I have an output of an command line operation which is stored in file and it 
> contains special characters. The file looks as below:
> 
> --------------------------------------------------------------
> 
> --->TestCase Command: add-route dest-ip subnet 22.12.23.44 subnetmask 
> 255.255.255.255 nexthop-ip 192.168.22.98
> interface ppd0^G
> iprouting> add-route dest-ip subnet 22.12.23.44 subnetmask 255.255.255.255 
> ^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H^H$dest-ip 
...etc...

Judging from the subject line, you want to remove these control characters. 
Here goes:

   # read all data as one big string
   f = open(filename, "rb")
   data = f.read()

   # remove ^H
   import string
   data = string.replace(data, chr(8), "")

   # do something nice with data, e.g. write it back to file,
   # or display it, etc.

HTH,

-- 
Hans (base64.decodestring('d3VybXlAZWFydGhsaW5rLm5ldA=='))
# decode for email address ;-)
The Pythonic Quarter:: http://www.awaretek.com/nowak/
Kaa:: http://www.awaretek.com/nowak/kaa.html





More information about the Python-list mailing list