Remove no-printable characters in string

Roel Mathys rm at rm.net
Wed Dec 3 12:32:38 EST 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 )

s = "\x08toto\x00titi"
t = ''.join( [ i for i in s if i in printable or i.isalpha() ] )

=> t == 'tototiti'

or

replace = { '\x00' : ' ' }
t = ''.join( [ replace.get(i,i) for i in s
		if i in printable
		or i.isalpha() # to catch for example 'ë'
		or i in replace ] )

=> t == 'toto titi'





More information about the Python-list mailing list