在字节文本文件Python

时间:2019-06-21 11:32:47

标签: python string

我的数据来自子流程,并且在我收到的输出中:

样本:

helo, aawe.adam , by the w,: 12.1:\r\n . heesa1.\r\n,b'asdasd',nme.AAAA.\r\n

type=<class 'bytes'>

我想将其剥离成一行,然后仅提取两个字符之间的巴特,在此示例中为.(点)

预期结果:

adam , by the w,: 12
1:
heesa1
,b'asdasd',nme
AAAA

我也尝试过这种方法: Extracting text between two strings

但是我收到错误: TypeError: cannot use a string pattern on a bytes-like object

感谢建议 `

2 个答案:

答案 0 :(得分:1)

您需要解码字节才能正常工作。试试这个:

output = b'helo, aawe.adam , by the w,: 12.1:\r\n . heesa1.\r\n,b'asdasd',nme.AAAA.\r\n'
str = output.decode("utf-8")

然后,您可以尝试像以前一样提取数据。

答案 1 :(得分:0)

>>> o = b"helo, aawe.adam , by the w,: 12.1:\r\n . heesa1.\r\n,b'asdasd',nme.AAAA.\r\n"
>>> o.split(b".")
[b'helo, aawe', b'adam , by the w,: 12', b'1:\r\n ', b' heesa1', b"\r\n,b'asdasd',nme", b'AAAA', b'\r\n']

字符串拆分应该通过忽略拆分列表中的第一项和最后一项来帮助您。