Remove no-printable characters in string

Roel Mathys rm at rm.net
Thu Dec 4 18:07:57 CET 2003


Pascal wrote:
> Hello,
> 
> What's the best way to delete or replace no-printable characters in a string.
> i.e.: "\x08toto\x00titi" -> "tototiti" or " toto titi"

import string
import sets
printable = sets.Set( string.printable )



def f1( s ) :
     return ''.join( [ i for i in s if i in printable or i.isalpha() ] )

def f2( s ) :
     replace = { '\x00' : ' ' }
     t = ''.join(
             [ replace.get(i,i)
               for i in s
               if i in printable
               or i.isalpha() # for non ascii characters
               or i in replace
             ] )

s = "\x08toto\x00titi"

t1 = f1(s) => 'tototiti'
t2 = f2(s) => 'toto titi'

works nicely, I think

bye,
roel





More information about the Python-list mailing list