在python2中初始化OS模块后,如何将str变量视为Unicode?

2024-09-25 02:30:39 发布

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

例如,您可以在初始化期间通过在字符串前面添加u来显式指定Unicode字符串,如下所示:

path1 = u'./테스트'
# printing type of path1 returns
<type 'unicode'>

另一方面,如果要将其初始化为普通字符串

path2 = './테스트'
# printing type of path2 returns
<type 'str'>

例如,如果我将path变量传递给os.listdir()函数以获取目录中的文件

path1工作正常,而path2抛出错误UnicodeDecodeError

我尝试使用decode转换path2,并将其传递给os.listdir()

path3 = path2.decode('unicode-escape')
#printing type of path3 returns
<type 'unicode'>
#but passing it to os.listdir() threw the following error
WindowsError: [Error 3]

path变量的检查显示解码改变了path3的值

path1 = ./테스트
path2 = ./테스트
path3 = ./íì¤í¸

导致系统抱怨没有名为./íì¤í
那我还缺什么?有没有其他方法可以将字符串变量转换为unicode?你知道吗


Tags: ofpath字符串ostypeunicodereturnslistdir
1条回答
网友
1楼 · 发布于 2024-09-25 02:30:39

'unicode-escape'不会做任何有用的事情,除非字符串包含Unicode转义。对于用字符集编码的普通文本,改为用该字符集解码。你知道吗

>>> './테스트'.decode('utf8')
u'./\ud14c\uc2a4\ud2b8'
>>> print './테스트'.decode('utf8')
./테스트

相关问题 更多 >