在 Python 中将字符串转换为 Unicode
本教程将讨论在 Python 中将常规字符串转换为 Unicode 字符串。
在 Python 2 中将字符串转换为 Unicode
在 Python 2 中,常规字符串称为字节字符串,我们可以使用内置的 unicode()
函数 将这些字节字符串转换为 Unicode 字符串。此代码片段向我们展示了如何在 Python 2 中将常规字符串转换为 Unicode 字符串。
regular = "regular string"
unicode_string = unicode(regular, "utf-8")
print(type(regular))
print(type(unicode_string))
输出:
<type 'str'>
<type 'unicode'>
我们使用 Python 2 中的 unicode()
函数将常规字节字符串转换为 Unicode 字符串。
在 Python 3 中将字符串转换为 Unicode 格式
在 Python 3 中,默认情况下字符串是 Unicode 字符串,我们无法将常规字符串转换为 Unicode 字符串。因此,以下代码在 Python 2 和 Python 3 上给出了不同的结果。
regular = "regular string"
unicode_string = u"Unicode string"
print(type(regular))
print(type(unicode_string))
Python 2 输出:
<type 'str'>
<type 'unicode'>
Python 3 输出:
<class 'str'>
<class 'str'>
在上面的代码中,我们在 Python 2 和 Python 3 中都初始化了一个 Unicode 字符串。在 Python 2 中,字符串属于 unicode
类,因为常规字符串和 Unicode 字符串之间存在区别,而在 Python 3 中,字符串属于类 str
。毕竟,Unicode 字符串与常规字符串相同。
声明:本站所有文章,如无特殊说明或标注,均为本站原创发布,任何个人或组织,在未征得本站同意时,禁止复制、盗用、采集、发布本站内容到任何网站。本站所有源码与软件均为原作者提供,仅供学习和研究使用。如您对本站的相关版权有任何异议,或者认为侵犯了您的合法权益,请及时通知我们处理。