python3脚本中可以使用哪些unicode字符?

lan*_*don 0 python unicode python-3.x python-unicode

一些 unicode 字符可用于命名变量、函数等,没有任何问题,例如?。

>>> ? = "Hello world!"
>>> print(?)
Hello world!
Run Code Online (Sandbox Code Playgroud)

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

>>> ? = "Hello world"
  File "<stdin>", line 1
    ?
    ^
SyntaxError: invalid character '?' (U+2207)
Run Code Online (Sandbox Code Playgroud)

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

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

Sni*_*kow 5

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'
>>> 
Run Code Online (Sandbox Code Playgroud)

? 被归类为“字母,小写”,而 ? 是一个“符号,数学”。前一类在标识符中是允许的,但后者不是。顶部的文档链接中提供了允许的字符类别的完整列表。