$字符在Python中代表变量名或标识符的一部分。

huangapple go评论103阅读模式
英文:

What is $ character to Python?

问题

Python 中的美元符号 $ 在除了字符串之外的地方并没有定义的用途,也不是为将来保留的。实验性地使用它会导致语法错误。任何其他可见的 Unicode 字符(不确定正确的 Unicode 术语)都可以作为变量名的一部分被接受(适用于 Python 3)。

例如:

>>>= 44
>>>44

但是,如果尝试使用 $ 符号作为变量名,会导致语法错误,如下所示:

>>> a$ = 27
File "<stdin>", line 1
  a$ = 27
   ^
SyntaxError: invalid syntax
英文:

I just realized I had never seen a dollar $ character in Python, other than in a string. Does it have any defined usage, or is it reserved for future use? Google doesn't provide an answer. Experimentally it causes syntax errors. Just about any other "visible" unicode (not sure of correct unicode terminology) is accepted as part of a variable name (Python 3)

&gt;&gt;&gt; aμ = 44
&gt;&gt;&gt; aμ
44

&gt;&gt;&gt; a$=27
  File &quot;&lt;stdin&gt;&quot;, line 1
    a$=27
     ^
 SyntaxError: invalid syntax

答案1

得分: 3

根据词法分析文档

> 以下打印的ASCII字符在Python中未使用。它们在字符串文字和注释之外的出现是一个无条件的错误:

> $ ? `

美元符号,问号和反引号在Python中简单地未被使用。

对于变量名(标识符)具体来说(重点是我的):

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

也就是说,虽然Python 3 在标识符中添加了对ASCII范围之外的其他Unicode字符的支持,但该范围内的其他字符(包括$)仍然不受支持。

英文:

Per the lexical analysis documentation:

> The following printing ASCII characters are not used in Python. Their
> occurrence outside string literals and comments is an unconditional
> error:
>
> $ ? `

The dollar sign, along with question mark and backtick, is simply unused in Python.

For variable names (identifiers) specifically (emphasis mine):

> Within the ASCII range (U+0001..U+007F), the valid characters for identifiers are the same as in Python 2.x: the uppercase and lowercase
> letters A through Z, the underscore _ and, except for the first
> character, the digits 0 through 9.

That is, although Python 3 added support for additional Unicode characters outside the ASCII range in identifiers, other characters inside that range (including $) are still not supported.

huangapple
  • 本文由 发表于 2023年6月29日 17:48:58
  • 转载请务必保留本文链接:https://go.coder-hub.com/76579922.html
匿名

发表评论

匿名网友

:?: :razz: :sad: :evil: :!: :smile: :oops: :grin: :eek: :shock: :???: :cool: :lol: :mad: :twisted: :roll: :wink: :idea: :arrow: :neutral: :cry: :mrgreen:

确定