【发布时间】:2019-11-11 04:36:09
【问题描述】:
我想要一个可以清理字符串的函数。清理程序返回的字符串应该只包含 ASCII 字符 #32(空格字符)到 ASCII #126('~')。
ASCII 字符#9(制表符)将替换为四个空格。所有其他非法字符都将替换为空字符串。例如,“\n”将被替换为空字符串。我们不希望非法字符被表示相关转义序列的字符串替换。例如,我们确实不希望将换行符替换为反斜杠字符和“n”字符。
如果最终的字符串是 Unicode 编码的,而不是 ASCII 编码,那就没问题了。我只希望唯一允许的字符如下:
" !\"#$%&'()*+,-./0123456789:;<=>?@ABCDEFGHIJKLMNOPQRSTUVWXYZ[\\]^_`abcdefghijklmnopqrstuvwxyz{|}~"
示例用法:
unsafe_string = "\u2502\u251cAPPLES\n\t\t\t\t\t\r\r AND \n\nBANANAS"
safe_string = sanitize(unsafe_string)
print(safe_string)
输出:
APPLES AND BANANAS
编辑:
以下尝试的解决方案不起作用,因为它们无法过滤掉换行符。
import string
import re
unsafe_string = "\u2502\u251cAPPLES\n\t\t\t\t\t\r\r AND \n\nBANANAS"
safe_string = re.sub(r'[^\x00-\x7f]',r'', unsafe_string)
print(safe_string)
printable = set(string.printable)
safe_string = ''.join(filter(lambda x: x in printable, unsafe_string))
print(safe_string)
【问题讨论】: