Python 函数名中允许的字符

Posted

技术标签:

【中文标题】Python 函数名中允许的字符【英文标题】:Allowed characters in Python function names 【发布时间】:2013-10-29 05:58:51 【问题描述】:

除了字母字符、数字和下划线之外,Python 函数名称中是否还有其他允许的字符?如果是,它们是什么?

【问题讨论】:

谷歌搜索:pasteur.fr/formation/infobio/python/ch02s03.html Valid characters in a python class name的可能重复 What is the naming convention in Python for variable and function names?的可能重复 @danny 常规 != 允许。 @delnan 你是对的。 【参考方案1】:

In Python 3 many characters are allowed:

identifier   ::=  xid_start xid_continue*
id_start     ::=  <all characters in general categories Lu, Ll, Lt, Lm, Lo, Nl, 
                   the underscore, and characters with the Other_ID_Start property>
id_continue  ::=  <all characters in id_start, plus characters in the categories 
                   Mn, Mc, Nd, Pc and others with the Other_ID_Continue property>
xid_start    ::=  <all characters in id_start whose NFKC normalization 
                   is in "id_start xid_continue*">
xid_continue ::=  <all characters in id_continue whose NFKC normalization 
                   is in "id_continue*">

The Unicode category codes mentioned above stand for:

Lu - uppercase letters
Ll - lowercase letters
Lt - titlecase letters
Lm - modifier letters
Lo - other letters
Nl - letter numbers
Mn - nonspacing marks
Mc - spacing combining marks
Nd - decimal numbers
Pc - connector punctuations
Other_ID_Start - explicit list of characters in PropList.txt 
                 to support backwards compatibility
Other_ID_Continue - likewise

每个角色的完整列表可以在Unicode.org找到。


在 Python 2.x 中,它仅限于字母、数字和下划线。来自the docs:

identifier ::=  (letter|"_") (letter | digit | "_")*
letter     ::=  lowercase | uppercase
lowercase  ::=  "a"..."z"
uppercase  ::=  "A"..."Z"
digit      ::=  "0"..."9"

【讨论】:

指向任何版本的 Python 3.x 文档,答案是肯定的 :) 例如:docs.python.org/3.2/reference/lexical_analysis.html#identifiers @JonClements D'oh!已编辑。

以上是关于Python 函数名中允许的字符的主要内容,如果未能解决你的问题,请参考以下文章

如何限制文本框中允许的字符数?

测试每个页面不超过 Symfony 中允许的 SQL 计数?

php数组键中允许的字符?

限制表单输入文本字段中允许的字符数

Google ID C2DM 中允许的字符

对C加深理解