Fla*_*ius 40 python python-3.x
如何将字节字符串拆分为行列表?
在python 2我有:
rest = "some\nlines"
for line in rest.split("\n"):
print line
Run Code Online (Sandbox Code Playgroud)
上面的代码是为了简洁起见而简化的,但现在经过一些正则表达式处理后,我有一个字节数组rest,我需要迭代这些行.
Jan*_*sen 84
没有理由转换为字符串.只需给出split字节参数.用字符串拆分字符串,用字节表示字节.
Python 3.2.3 (default, Oct 19 2012, 19:53:57)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = b'asdf\nasdf'
>>> a.split(b'\n')
[b'asdf', b'asdf']
Run Code Online (Sandbox Code Playgroud)
war*_*iuc 19
将字节解码为unicode(str),然后使用str.split:
Python 3.2.3 (default, Oct 19 2012, 19:53:16)
[GCC 4.7.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> a = b'asdf\nasdf'
>>> a.split('\n')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Type str doesn't support the buffer API
>>> a = a.decode()
>>> a.split('\n')
['asdf', 'asdf']
>>>
Run Code Online (Sandbox Code Playgroud)
你也可以拆分b'\n',但我想你必须使用字符串而不是字节.因此str,请尽快转换所有输入数据,并仅在代码中使用unicode,并在需要时尽可能将其转换为字节.
| 归档时间: |
|
| 查看次数: |
51315 次 |
| 最近记录: |