easy way to remove nonprintable chars from string

D

Don Hiatt

Greetings,

Is there an easy way to remove multiple non-printable
(e.g. "not strings.printable") from a string? Perhaps
something like foo.replace(list_of_nonprintables, '')
if it only existed? :)

Cheers,

don
 
S

Skip Montanaro

Don> Is there an easy way to remove multiple non-printable (e.g. "not
Don> strings.printable") from a string? Perhaps something like
Don> foo.replace(list_of_nonprintables, '') if it only existed? :)

Check out the string module's translate function.

Skip
 
I

Isaac Raway

This seems to work. Not sure how fast it'd be, though.

def stripNoPrint(str):
results = ""
for char in str:
if string.printable.find(char):
results += char
return results
 
T

Terry Reedy

Don Hiatt said:
Is there an easy way to remove multiple non-printable
(e.g. "not strings.printable") from a string? Perhaps
something like foo.replace(list_of_nonprintables, '')
if it only existed? :)
translate(...)
S.translate(table [,deletechars]) -> string

Return a copy of the string S, where all characters occurring
in the optional argument deletechars are removed, and the
remaining characters have been mapped through the given
translation table, which must be a string of length 256.
s_identity=''.join([chr(i) for i in range(256)]) # the 'table' you
need

Terry J. Reedy
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,734
Messages
2,569,441
Members
44,832
Latest member
GlennSmall

Latest Threads

Top