如何在Python中的非打印ascii字符处分割线

Don*_*ied 3 python ascii split extended-ascii

如何在 Python 中以非打印 ascii 字符(例如长减号十六进制 0x97 ,八进制 227 )分割一行?我不需要角色本身。其后的信息将保存为变量。

mik*_*iku 5

您可以使用re.split.

>>> import re
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
Run Code Online (Sandbox Code Playgroud)

调整模式以仅包含您要保留的字符。

另见:stripping-non-printable-characters-from-a-string-in-python


示例(带长减):

>>> # \xe2\x80\x93 represents a long dash (or long minus)
>>> s = 'hello – world'
>>> s
'hello \xe2\x80\x93 world'
>>> import re
>>> re.split("\xe2\x80\x93", s)
['hello ', ' world']
Run Code Online (Sandbox Code Playgroud)

或者,与 unicode 相同:

>>> # \u2013 represents a long dash, long minus or so called en-dash
>>> s = u'hello – world'
>>> s
u'hello \u2013 world'
>>> import re
>>> re.split(u"\u2013", s)
[u'hello ', u' world']
Run Code Online (Sandbox Code Playgroud)