Python读取二进制文件,二进制数据到字符串?

mow*_*ker 0 python string binary

我正在尝试学习Python,目前正在网上做一些练习.其中一个涉及读取zip文件.

当我做:

import zipfile
zp=zipfile.ZipFile('MyZip.zip')
print(zp.read('MyText.txt'))
Run Code Online (Sandbox Code Playgroud)

它打印:

b'Hello World'
Run Code Online (Sandbox Code Playgroud)

我只想要一个带有"Hello World"的字符串.我知道这很愚蠢,但我能想到的唯一方法就是:

import re
re.match("b'(.*)'",zp.read('MyText.txt'))
Run Code Online (Sandbox Code Playgroud)

我该怎么办呢?

Bra*_*des 6

您需要将字符串中的原始字节解码为实际字符.尝试在打印之前运行.decode('utf-8')您要返回的值zp.read().


Ign*_*ams 5

您需要先将字节解码为文本.

print(zp.read('MyText.txt').decode('utf-8'))
Run Code Online (Sandbox Code Playgroud)


phi*_*hag 5

只需解码字节:

print(zp.read('MyText.txt').decode('UTF-8'))
Run Code Online (Sandbox Code Playgroud)