首页 > 解决方案 > python3脚本中可以使用哪些unicode字符?

问题描述

一些 unicode 字符可以毫无问题地用于命名变量、函数等,例如 α。

>>> α = "Hello world!"
>>> print(α)
Hello world!

其他 unicode 字符会引发错误,例如 ∇。

>>> ∇ = "Hello world"
  File "<stdin>", line 1
    ∇
    ^
SyntaxError: invalid character '∇' (U+2207)

哪些 unicode 字符可用于在 python 中形成有效的表达式?哪些 unicode 字符会引发 SyntaxError?

而且,是否有一种合理的方法可以在 python 脚本中包含引发错误的 unicode 字符?我想在计算梯度的函数名称中使用∇,例如,∇f 来表示 f 的梯度。

标签: pythonpython-3.xunicodepython-unicode

解决方案


https://docs.python.org/3/reference/lexical_analysis.html#identifiers说:

在 ASCII 范围 (U+0001..U+007F) 内,标识符的有效字符与 Python 2.x 中的相同:大写和小写字母 A 到 Z、下划线 _ 以及除第一个字符外,数字 0 到 9。

Python 3.0 引入了 ASCII 范围之外的其他字符(请参阅PEP 3131)。对于这些字符,分类使用包含在unicodedata模块中的 Unicode 字符数据库的版本。

让我们检查您的特定字符:

~$ python3
Python 3.6.9 (default, Jan 26 2021, 15:33:00) 
[GCC 8.4.0] on linux
Type "help", "copyright", "credits" or "license" for more information.
>>> import unicodedata
>>> unicodedata.category('α')
'Ll'
>>> unicodedata.category('∇')
'Sm'
>>> 

α 被归类为“字母,小写”,而 ∇ 是“符号,数学”。前一类在标识符中是允许的,但后一类是不允许的。允许的字符类别的完整列表可在顶部的文档链接中找到。


推荐阅读