Most direct way to strip unoprintable characters out of a string?

Steve Bergman steve at
Sun Sep 25 06:04:32 CEST 2005

George Sakkis wrote:

>If by straightforward you mean one-liner, there is:
>''.join(c for c in input_string if c not in string.printable)
>If you care about performance though, string.translate is faster; as always, the best way to decide
>on a performance issue is to profile the alternatives on your data and see if it's worth going for
>the fastest one at the expense of readability.
Thank you for the reply.  I was really thinking of some function in the 
standard library like:

s = stripUnprintable(s)

When I learned php, I more or less took the route of using whatever I 
found that 'worked'.  In learning Python, I'm trying to take my time and 
learn the 'right' (that's pronounced 'beautiful') way of doing things.

As it stands, I've stashed the string.translate code in a short function 
with a comment explaining what it does and how.  I mainly didn't want to 
use that if there was some trivial built-in that everyone else uses.

Thanks Again,

More information about the Python-list mailing list