如何在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 2026年春节祝福语简短
12 公司商务中秋祝福语简短
13 除夕的拜年祝福语简短
14 启程出发路途祝福语简短
15 诗词文案祝福语简短精辟
16 护士辞职送行祝福语简短
17 20岁简短生日祝福语
18 虎年台词祝福语大全简短