从python3文件中读取字节字符串

2024-10-01 15:45:39 发布

您现在位置:Python中文网/ 问答频道 /正文

文件内容如下,文件编码为utf-8:

cd232704-a46f-3d9d-97f6-67edb897d65f    b'this Friday, Gerda Scheuers will be excited \xe2\x80\x94 but she\xe2\x80\x99s most excited about the merchandise the movie will bring.'

这是我的代码:

^{pr2}$

我想得到一个正确的答案-“这个星期五,格尔达·谢尔斯会很兴奋的,但她最兴奋的是电影将带来的商品。”

print(b'\xe2\x80\x94'.decode('utf-8')) #convert into ASCII 

但我不能从文件中读取字节。如果我打开一个有字节的文件,我需要解码该行来拆分它。在


Tags: 文件the内容编码字节thiswillutf
1条回答
网友
1楼 · 发布于 2024-10-01 15:45:39

可以使用^{}将字节文本转换为字节:

然后,对其进行解码以获得字符串对象:

>>> ast.literal_eval(r"b'excited \xe2\x80\x94 but she\xe2\x80\x99s'")
b'excited \xe2\x80\x94 but she\xe2\x80\x99s'
>>> ast.literal_eval(r"b'excited \xe2\x80\x94 but she\xe2\x80\x99s'").decode('utf-8')
'excited — but she’s'

^{pr2}$

相关问题 更多 >

    热门问题