如何在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 生日开业蛋糕祝福语简短