如何在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
热门推荐
1 如何训练狗狗不叫
2 训练狗狗不叫
3 训练狗狗随行
4 怎么训练狗狗不叫
7 训练比熊狗狗教程
10 上海狗狗训练
11 怎么训练狗狗上厕所
12 训练狗狗趴下
13 狗狗服从训练
14 训练狗狗拒食
15 训练狗狗笑
16 训练狗狗大便
17 训练狗狗立
18 训练狗狗捡东西