如何在Python中修剪掉字符串中不可打印的字符?
如果只有ASCII字符,并且要删除不可打印的字符,最简单的方法是使用string.printable过滤掉那些字符。例如,
>>> import string >>> filter(lambda x: x in string.printable, '\x01string') string
未打印0x01,因为它不是可打印字符。如果还需要支持Unicode,则需要使用Unicode数据模块和正则表达式删除这些字符。
示例
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'))输出结果
这将给出输出:
String
热门推荐
10 圣诞祝福语简短小学
11 祖国七十华诞简短祝福语
12 老师送的祝福语简短
13 生日祝福语大全女生简短
14 祝女性生日祝福语简短
15 牛年女神节祝福语简短
16 情人表白祝福语简短大气
17 老公开业祝福语简短
18 官宣新年祝福语简短