如何从python3中的'二进制字符串'中提取子字符串

时间:2017-11-09 06:33:22

标签: python python-3.x

我有一个字符串b'helloworld\n'。我想从中提取helloworld。为此,我正在做

print(string[1:-2])

但是在输出上我得到了b'elloworl'

我怎样才能将文字提升为helloworld。

由于

2 个答案:

答案 0 :(得分:1)

print(s[0:-1])

索引为零,因此h处于零指数。结束索引是非包容性的,所以再多做一次。

如果你想摆脱b,你必须解码字节对象。

print(s.decode('utf-8')[0:-1])

答案 1 :(得分:-1)

this link开始,要将二进制字符串更改为普通字符串,请使用以下命令:

>>> b'helloworld\n'.decode('ascii') # you can use utf8 or something else, it is up to you
'helloworld\n'

要删除空格,请使用strip()

>>> b'helloworld\n'.decode('ascii').strip()
'helloworld'