如何在Python中按非打印ASCII字符拆分行
我想知道怎么在Python中把一行文本分开,分开的地方是一个看不见的ASCII字符,比如长的减号(它的十六进制表示是0x97,八进制是227)。我不需要这个字符本身,只想把它后面的信息保存到一个变量里。
3 个回答
1
只需要使用字符串或Unicode的分割方法就可以了(他们其实并不在乎你用什么来分割,只要是个常量就行。如果你想用正则表达式,那就用re.split)。
要获取分割后的字符串,可以像其他人展示的那样进行转义,比如用"\x97"。
或者
你也可以用chr(0x97)来处理字符串(范围是0到255),或者用unichr(0x97)来处理Unicode。
举个例子:
'will not be split'.split(chr(0x97))
'will be split here:\x97 and this is the second string'.split(chr(0x97))
2
_, _, your_result= your_input_string.partition('\x97')
或者
your_result= your_input_string.partition('\x97')[2]
如果你的输入字符串中没有 '\x97'
这个字符,那么 your_result
就会是空的。如果你的输入字符串中有多个 '\x97'
字符,那么 your_result
会包含第一个 '\x97'
字符之后的所有内容,包括其他的 '\x97'
字符。
5
你可以使用 re.split
这个功能。
>>> import re
>>> re.split('\W+', 'Words, words, words.')
['Words', 'words', 'words', '']
调整一下规则,只保留你想要的字符。
另外,你可以看看这个链接: 在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']