首頁  >  文章  >  後端開發  >  如何在 Python 中從字串中刪除不可列印的字元?

如何在 Python 中從字串中刪除不可列印的字元?

DDD
DDD原創
2024-10-22 06:55:02421瀏覽

How to Strip Non-Printable Characters from Strings in Python?

從Python 中的字串中移除不可列印的字元

在Perl 中,s/[^[:print:]] // g 正規表示式有效地從字串中刪除所有無法列印的字元。然而,在 Python 中,沒有等效的 POSIX 正規表示式類,讓一些人想知道如何完成相同的任務。

理解 Unicode

挑戰在於處理 Unicode 字符,因為 string.printable 方法可能會無意中將它們刪除。

建立自訂字元類別

為了解決這個問題,我們可以使用 unicodedata 建構一個自訂字元類別模組。 unicodedata.category() 函數提供對字元類別的深入了解。例如,我們可以定義一個名為 control_characters 的字元類,透過從 Unicode 字元集中過濾掉這些類別來表示不可列印的字符,例如控製字元和代理字元。

<code class="python">import unicodedata
import re

categories = {'Cc', 'Cf', 'Cs'}  # Include desired categories here
control_chars = ''.join(chr(i) for i in range(sys.maxunicode) if unicodedata.category(chr(i)) in categories)
control_char_re = re.compile('[%s]' % re.escape(control_chars))</code>

與迭代字串。

<code class="python">def remove_control_chars(s):
    return control_char_re.sub('', s)</code>

額外自訂

對於需要過濾其他類別(例如私人使用字元)的場景,您可以擴充字元類別

<code class="python">categories.add('Co')  # Add private-use characters
# Rebuild the character class and regex</code>

透過利用這種方法,您可以有效地從Python 中的Unicode 字串中去除不可列印的字符,滿足基本和自訂用例。

以上是如何在 Python 中從字串中刪除不可列印的字元?的詳細內容。更多資訊請關注PHP中文網其他相關文章!

陳述:
本文內容由網友自願投稿,版權歸原作者所有。本站不承擔相應的法律責任。如發現涉嫌抄襲或侵權的內容,請聯絡admin@php.cn