How to trim down non printable characters from a string in Python?

PythonServer Side ProgrammingProgramming

If you have only ASCII characters and want to remove the non-printable characters, the easiest way is to filter out those characters using string.printable. For example,

>>> import string
>>> filter(lambda x: x in string.printable, '\x01string')

The 0x01 was not printed as it is not a printable character. If you need to support Unicode as well, then you need to use the Unicode data module and regexes to remove these characters.


import sys, unicodedata, re
# Get all unicode characters
all_chars = (unichr(i) for i in xrange(sys.maxunicode))
# Get all non printable characters
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) == 'Cc')
# Create regex of above characters
control_char_re = re.compile('[%s]' % re.escape(control_chars))
# Substitute these characters by empty string in the original string.
def remove_control_chars(s):
    return control_char_re.sub('', s)
print (remove_control_chars('\x00\x01String'))


This will give the output:

Updated on 13-Feb-2020 10:39:30