如何在Python3中将字符串转换成unicode?

2024-06-16 11:36:35 发布

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

我尝试了很多方法将b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a'等字符串转换成中文字符,但都失败了。在

真的很奇怪

print(b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a')

它将显示解码的汉字。在

但是如果我从CSV文件中读取字符串,就不行了。无论我如何解码字符串,它都只显示b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a'

这是我的剧本:

import csv 

with open('need_convert.csv','r+') as csvfile:
    reader=csv.reader(csvfile)
    for row in reader:

        new_row=''.join(row)
        print('new_row:')
        print(type(new_row))
        print(new_row)

        print('convert:')
        print(new_row.decode('utf-8'))

以下是我的数据(csv文件): b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a' b'\xef\xbb\xbf\xe9\xba\x92\xe9\xba\x9f\xe6\x9d\xaf' b'\xef\xbb\xbf\xe5\x9b\xbd\xe9\x99\x85\xe5\x8f\x8b\xe8\xb0\x8a'


Tags: rowprintxbdx8bxe5xe9x85xef
1条回答
网友
1楼 · 发布于 2024-06-16 11:36:35

row内容和new_row都是字符串,而不是字节类型。下面,我使用exec('s=' + row[0])根据需要解释它们,假设输入是安全的。在

import csv

with open('need_convert.csv','r+') as csvfile:
    reader=csv.reader(csvfile)
    for row in reader:
        print(type(row[0]), row[0])
        exec('s=' + row[0])
        print(type(s), s)
        print(s.decode('utf-8'))

输出:

^{pr2}$

相关问题 更多 >