【发布时间】:2010-05-29 18:36:43
【问题描述】:
如何在 Python 中以非打印 ascii 字符(例如长减号十六进制 0x97 、八进制 227)分割一行? 我不需要角色本身。后面的信息会保存为变量。
【问题讨论】:
标签: python split ascii extended-ascii
如何在 Python 中以非打印 ascii 字符(例如长减号十六进制 0x97 、八进制 227)分割一行? 我不需要角色本身。后面的信息会保存为变量。
【问题讨论】:
标签: python split ascii extended-ascii
您可以使用re.split。
>>> import re
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
调整模式以仅包含您想要保留的字符。
另见: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']
或者,与 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']
【讨论】:
_, _, your_result= your_input_string.partition('\x97')
或
your_result= your_input_string.partition('\x97')[2]
如果your_input_string 不包含'\x97',则your_result 将为空。如果your_input_string 包含多个 '\x97' 字符,则your_result 将包含第一个'\x97' 字符之后的所有内容,包括其他'\x97' 字符。
【讨论】:
只需使用字符串/unicode 拆分方法(他们并不真正关心您拆分的字符串(除了它是一个常量。如果您想使用正则表达式,请使用 re.split)
要获得拆分字符串,要么像其他人展示的那样将其转义 "\x97"
或
对字符串 (0-255) 使用 chr(0x97),对 unicode 使用 unichr(0x97)
举个例子
'will not be split'.split(chr(0x97))
'will be split here:\x97 and this is the second string'.split(chr(0x97))
【讨论】:
chr(0x97) ) (2) 使用[uni]chr(0x97) instead of [u]"\x97" 是混淆/冗余/浪费/可弃用(恕我直言)——你会写float("1.23") 而不是1.23? (3) 如果在unicode中操作,他不需要unichr(0x97),他需要u"\u2014",即"\x97".decode("cp1252")