数字文字的调用方法

编程入门 行业动态 更新时间:2024-10-26 14:40:21
本文介绍了数字文字的调用方法的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧! 问题描述

我可以在字符串文字上调用 str 方法.但是我不能在整数文字上调用 int 方法:

I can call str methods on string literal. But I cannot call int methods on a integer number literal:

Python 2.7.5+ (default, Sep 19 2013, 13:48:49) >>> 1.bit_length() File "<stdin>", line 1 1.bit_length() ^ SyntaxError: invalid syntax >>> a = 1 >>> a.bit_length() 1 >>> ', '.join(['1', '2']) '1, 2' >>>

这是为什么?

推荐答案

Python 将 1. 视为浮点数的开头,但无法解析该行的其余部分.改成

Python treats 1. as a beginning of a float number, but fails to parse the rest of the line. Change it to

(1).bit_length()

通过用括号括起数字文字,我们确保 python 计算括号内的表达式,即 1 并调用该数字的方法.

by enclosing the number literal with parenthesis, we make sure that python evaluates the expression within the parens, which is 1 and call the method on that number.

Python 像这样定义了浮点文字

Python defines floating point literal like this

floatnumber ::= pointfloat | exponentfloat pointfloat ::= [intpart] fraction | intpart "." exponentfloat ::= (intpart | pointfloat) exponent intpart ::= digit+ fraction ::= "." digit+ exponent ::= ("e" | "E") ["+" | "-"] digit+

根据该定义,词法分析器认为 1.bit_length() 将是一个浮点文字,因为 1. 匹配 [intpart] 分数 的开头.但该行的其余部分不匹配.这就是它失败的原因.

As per that definition, the lexical analyzer thinks that 1.bit_length() would be a float literal, since 1. matches the [intpart] fraction's beginning. But the rest of the line doesn't match. That is why it fails.

更多推荐

数字文字的调用方法

本文发布于:2023-05-27 02:45:31,感谢您对本站的认可!
本文链接:https://www.elefans.com/category/jswz/34/275031.html
版权声明:本站内容均来自互联网,仅供演示用,请勿用于商业和其他非法用途。如果侵犯了您的权益请与我们联系,我们将在24小时内删除。
本文标签:词库加载错误:Could not find file &#039;D:\淘小白 高铁采集器win10\Configuration\Dict_Sto

发布评论

评论列表 (有 0 条评论)
草根站长

>www.elefans.com

编程频道|电子爱好者 - 技术资讯及电子产品介绍!