python - 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 的梯度。
解决方案
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'
>>>
α 被归类为“字母,小写”,而 ∇ 是“符号,数学”。前一类在标识符中是允许的,但后一类是不允许的。允许的字符类别的完整列表可在顶部的文档链接中找到。
推荐阅读
- database - azure 上的防火墙规则
- python - 无法使用 QTableView / 自定义表格模型设置标题数据
- python - 使用 cython 获取当前时间(以毫秒为单位)
- python - 如何遍历 Pytest 中每个变量的所有测试?
- android - 将文件从外部存储文件夹复制到具有不同文件扩展名的同一文件夹中
- c# - 从 ASP.NET MVC 应用程序调用 ASP.NET Web API REST 服务时出现 HTTPClient 错误
- javascript - React:发送带有重定向问题的道具
- laravel - Laravel 数据表数据显示问题
- android - Android Studio 和 Kotlin - 在挂起函数中的运行时设置断点不起作用
- magento - 从 Observer Magento 1.9 设置产品自定义选项