gpt4 book ai didi

python - 在python中将字符串转换为unicode类型

转载 作者:太空狗 更新时间:2023-10-30 00:56:20 24 4
gpt4 key购买 nike

我正在尝试这段代码:

s = "سلام"
'{:b}'.format(int(s.encode('utf-8').encode('hex'), 16))

但是出现这个错误:

'{:b}'.format(int(s.encode('utf-8').encode('hex'), 16))

UnicodeDecodeError: 'ascii' codec can't decode byte 0xd3 in position 0: ordinal not in range(128)

我试过了 '{:b}'.format(int(s.encode('utf-8').encode('hex'), 16))但没有任何改变。

我该怎么办?

最佳答案

由于您使用的是 python 2,s = "سلام" 是一个字节字符串(无论您的终端使用何种编码,大概是 utf8):

>>> s = "سلام"
>>> s
'\xd8\xb3\xd9\x84\xd8\xa7\xd9\x85'

您不能编码 字节字符串(因为它们已经被“编码”)。您正在寻找 unicode(“真实”)字符串,在 python2 中必须以 u 为前缀:

>>> s = u"سلام"
>>> s
u'\u0633\u0644\u0627\u0645'
>>> '{:b}'.format(int(s.encode('utf-8').encode('hex'), 16))
'1101100010110011110110011000010011011000101001111101100110000101'

如果您从 raw_input 等函数中获取字节字符串,那么您的字符串已经编码 - 只需跳过 encode 部分:

'{:b}'.format(int(s.encode('hex'), 16))

或者(如果你打算用它做任何其他事情)将它转换为 unicode:

s = s.decode('utf8')

这假设您的输入是 UTF-8 编码的,如果不是这种情况,请先检查 sys.stdin.encoding

i10n 的东西很复杂,这里有两篇文章可以进一步帮助您:

关于python - 在python中将字符串转换为unicode类型,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19258729/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com