将字节字符串转换为 unicode 字符串 [英] Converting byte string in unicode string

查看:144
本文介绍了将字节字符串转换为 unicode 字符串的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我有这样的代码:

a = "\u0432"b = u"\u0432"c = b"\u0432"d = c.decode('utf8')打印(类型(a),a)打印(类型(b),b)打印(类型(c),c)打印(类型(d),d)

和输出:

√<类'str'>√<类'字节'>b'\\u0432'<类'str'>\u0432

为什么在后一种情况下我看到的是字符代码,而不是字符?如何将字节字符串转换为 Unicode 字符串,以便在输出时看到字符而不是其代码?

解决方案

在字符串(或 Python 2 中的 Unicode 对象)中,\u 有一个特殊的含义,即说,这里有一个 Unicode由其 Unicode ID 指定的字符".因此 u"\u0432" 将导致字符 в.

b'' 前缀告诉你这是一个 8 位字节的序列,bytes 对象没有 Unicode 字符,所以 \u 代码没有特殊意义.因此,b"\u0432" 只是字节序列 \,u,0,432.

本质上,您有一个 8 位字符串,其中不包含 Unicode 字符,而是包含 Unicode 字符的规范.

您可以使用 unicode 转义编码器转换此规范.

<预><代码>>>>c.decode('unicode_escape')' '

I have a code such that:

a = "\u0432"
b = u"\u0432"
c = b"\u0432"
d = c.decode('utf8')

print(type(a), a)
print(type(b), b)
print(type(c), c)
print(type(d), d)

And output:

<class 'str'> в
<class 'str'> в
<class 'bytes'> b'\\u0432'
<class 'str'> \u0432

Why in the latter case I see a character code, instead of the character? How I can transform Byte string to Unicode string that in case of an output I saw the character, instead of its code?

解决方案

In strings (or Unicode objects in Python 2), \u has a special meaning, namely saying, "here comes a Unicode character specified by it's Unicode ID". Hence u"\u0432" will result in the character в.

The b'' prefix tells you this is a sequence of 8-bit bytes, and bytes object has no Unicode characters, so the \u code has no special meaning. Hence, b"\u0432" is just the sequence of the bytes \,u,0,4,3 and 2.

Essentially you have an 8-bit string containing not a Unicode character, but the specification of a Unicode character.

You can convert this specification using the unicode escape encoder.

>>> c.decode('unicode_escape')
'в'

这篇关于将字节字符串转换为 unicode 字符串的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆