如何在Python中裁剪字符串中的不可打印字符?
如果您只有ASCII字符并希望删除不可打印字符,则最简单的方法是使用string.printable过滤掉那些字符。例如,
>>> import string
>>> filter(lambda x: x in string.printable, '\x01string')
string
由于0x01不是可打印字符,因此其未被打印。如果您还需要支持Unicode,则需要使用Unicode数据模块和正则表达式来删除这些字符。
更多Python相关文章,请阅读:Python 教程
示例
import sys, unicodedata, re
# 获取所有Unicode字符
all_chars = (unichr(i) for i in xrange(sys.maxunicode))
# 获取所有非打印字符
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) == 'Cc')
# 创造正则表达式
control_char_re = re.compile('[%s]' % re.escape(control_chars))
# 将这些字符替换为空字符串
def remove_control_chars(s):
return control_char_re.sub('', s)
print (remove_control_chars('\x00\x01String'))
输出
这将给出以下输出:
String