gpt4 book ai didi

声明为 utf-8 的模块中的 Python unicode 字符串文字

转载 作者:太空狗 更新时间:2023-10-30 00:29:58 25 4
gpt4 key购买 nike

我有一个带有 utf-8 header 的虚拟 Python 模块,如下所示:

# -*- coding: utf-8 -*-
a = "á"
print type(a), a

打印:

<type 'str'> á

但我认为声明为 utf-8 的 Python 模块内的所有字符串文字都自动属于 unicode 类型,而不是 str。我是否遗漏了什么或者这是正确的行为吗?

为了将 a 作为 unicode 字符串,我使用:

a = u"á"

但这看起来不太“礼貌”,也不实用。有更好的选择吗?

最佳答案

# -*- coding: utf-8 -*-

不会使字符串文字成为 Unicode。举个例子,我有一个带有阿拉伯语注释和字符串的文件,文件是 utf-8:

# هذا تعليق عربي
print type('نص عربي')

如果我运行它,它会抛出 SyntaxError异常:

SyntaxError: Non-ASCII character '\xd9' in file file.py
on line 2, but no encoding declared;
see http://www.python.org/peps/pep-0263.html for details

因此,为了允许这样做,我必须添加该行以告诉解释器该文件是 UTF-8 编码的:

# -*-coding: utf-8 -*-

# هذا تعليق عربي
print type('نص عربي')

现在它运行良好但它仍然打印 <type 'str'>除非我制作字符串 Unicode:

# -*-coding: utf-8 -*-

# هذا تعليق عربي
print type(u'نص عربي')

关于声明为 utf-8 的模块中的 Python unicode 字符串文字,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/19771015/

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