为什么是“1.real"?语法错误,但“1 .real"在 Python 中有效吗? [英] Why is "1.real" a syntax error but "1 .real" valid in Python?

查看:64
本文介绍了为什么是“1.real"?语法错误,但“1 .real"在 Python 中有效吗?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

所以我看到了这两个 推特上的问题.1.real 如何是语法错误而 1 .real 不是?

<预><代码>>>>1.真实文件<stdin>",第 1 行1.真实^语法错误:无效语法>>>1 .real1>>>1. 真实文件<stdin>",第 1 行1. 真实^语法错误:无效语法>>>1 .真实的1>>>1..真实1.0>>>1 ..真实文件<stdin>",第 1 行1 ..真实^语法错误:无效语法>>>1.. 真实的1.0>>>1 .. 真实的文件<stdin>",第 1 行1 .. 真实的^语法错误:无效语法

解决方案

我猜 . 被贪婪地解析为数字的一部分,如果可能,使其成为 floatcode> 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 中有效吗?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆