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

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

Susan Sarandon
Susan Sarandon原創
2024-10-22 06:58:30305瀏覽

How to Remove Non-Printable Characters from Python Strings?

從Python 中的字符串中刪除不可打印的字符

問題:

在Perl 中,可以使用正規表示式s/[^[:print:]]//g 刪除不可列印的字元。但是,在 Python 中,不支援 [:print:] 類別。我們如何在Python中實現類似的同時處理ASCII和Unicode字元的功能?

答案:

由於Python在偵測可列印性方面的限制,我們可以建構自己的字元使用 unicodedata 模組的類別。

<code class="python">import unicodedata, re, itertools, sys

# Generate a list of all characters
all_chars = (chr(i) for i in range(sys.maxunicode))

# Category of control characters
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)

# Escape the control characters for regular expression matching
control_char_re = re.compile('[%s]' % re.escape(control_chars))

# Function to remove control characters from a string
def remove_control_chars(s):
    return control_char_re.sub('', s)</code>

對於Python 2:

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

# Generate a list of all characters
all_chars = (unichr(i) for i in xrange(sys.maxunicode))

# Category of control characters
categories = {'Cc'}
control_chars = ''.join(c for c in all_chars if unicodedata.category(c) in categories)

# Escape the control characters for regular expression matching
control_char_re = re.compile('[%s]' % re.escape(control_chars))

# Function to remove control characters from a string
def remove_control_chars(s):
    return control_char_re.sub('', s)</code>

擴充選項:

擴充選項:

包含其他類別,儘管這可能會影響效能。

  • 字元類別與計數:
  • 副本(控制):65
  • Cf(格式):161
  • Cf(格式):161
Cs(代理):2048Co(私人使用):137468Cn(未分配):836601

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

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