问题描述
所以我看到了这两个 推特上的问题.1.real
如何是语法错误而 1 .real
不是?
我猜 .
被贪婪地解析为数字的一部分,如果可能,使其成为 float
code> 1.
,而不是方法调用的一部分.
小数点周围不允许有空格,但在方法调用中,.
前后可以有空格.如果数字后跟一个空格,则数字的解析终止,所以它是明确的.
让我们看看不同的情况以及它们是如何解析的:
>>>1.real # 解析为 (1.)real ->丢失的 '.'>>>1 .real # 解析为 (1).real ->好的>>>1. real # 解析为 (1.)real ->丢失的 '.'>>>1 .real # 解析为 (1).real ->好的>>>1..real # 解析为 (1.).real ->好的>>>1 ..real # 解析为 (1)..real ->一 '.'太多了>>>1.. real # 解析为 (1.).real ->好的>>>1 .. real # 解析为 (1)..real ->一 '.'太多了So I saw these two questions on twitter. How is 1.real
a syntax error but 1 .real
is not?
>>> 1.real
File "<stdin>", line 1
1.real
^
SyntaxError: invalid syntax
>>> 1 .real
1
>>> 1. real
File "<stdin>", line 1
1. real
^
SyntaxError: invalid syntax
>>> 1 . real
1
>>> 1..real
1.0
>>> 1 ..real
File "<stdin>", line 1
1 ..real
^
SyntaxError: invalid syntax
>>> 1.. real
1.0
>>> 1 .. real
File "<stdin>", line 1
1 .. real
^
SyntaxError: invalid syntax
I guess that the .
is greedily parsed as part of a number, if possible, making it the float
1.
, instead of being part of the method call.
Spaces are not allowed around the decimal point, but you can have spaces before and after the .
in a method call. If the number is followed by a space, the parse of the number is terminated, so it's unambiguous.
Let's look at the different cases and how they are parsed:
>>> 1.real # parsed as (1.)real -> missing '.'
>>> 1 .real # parsed as (1).real -> okay
>>> 1. real # parsed as (1.)real -> missing '.'
>>> 1 . real # parsed as (1).real -> okay
>>> 1..real # parsed as (1.).real -> okay
>>> 1 ..real # parsed as (1)..real -> one '.' too much
>>> 1.. real # parsed as (1.).real -> okay
>>> 1 .. real # parsed as (1)..real -> one '.' too much
这篇关于为什么是“1.real"?语法错误,但“1 .real"在 Python 中有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持!