Computer >> บทช่วยสอนคอมพิวเตอร์ >  >> การเขียนโปรแกรม >> Python

วิธีตัด Non-printable Characters ออกจาก String ใน Python

กรณี ASCII เท่านั้น: ใช้ string.printable กรองตัวอักษร

>> import string
>>> ''.join(filter(lambda x: x in string.printable, '\x01string'))
'string'

รองรับ Unicode: ใช้ unicodedata และ regex

ตัวอย่างโค้ด

import sys, unicodedata, re

# สร้าง regex ของ control characters (category Cc)
all_chars = (chr(i) for i in range(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