繁体   English   中英

integer 的长度,在 python 中带有前导零

[英]Length of an integer with leading zeros in python

如何找到 integer 的长度。 有很多解决方案,我用过(int(math.log10(TheNumber))+1) 但如果数字是 '0111',它在 python 2.7 和 python 3.* 中返回为 '1'。* 它返回'SyntaxError: leading zeroes in a decimal number is not permitted' 但是'0111'是'111'。 但是使用len(str(number))给出了正确的长度。 对此的任何解决方案..

只是想澄清一下。 提前致谢

抱歉,问题中的信息很少。 问题是,0111,这个数字的长度是 3,但是当我检查这个 integer 的长度时,在 python 2.7 中,它返回 2。代码是

a = 0111

print(len(str(a)))

它返回 2 作为答案,当我在 python3.* 中运行上述相同代码时,它显示为SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers

在我的程序中,如果用户给出这种数字,即带有前导零的数字,我应该如何将其转换为没有前导零的数字。

我的输入 = 0111

转换输入=111

在 python 2.7 中,它被认为是八进制数,当我打印它时,它返回73在 python 3.* 中它要求八进制表示(SyntaxError)。 如果我使用另一种方法int(math.log10(TheNumber))+1

import math
a = 0111
print(int(math.log10(a))+1)

在 python 2.7 中,它返回 2,隐式转换为八进制数。 在 python 3.* 中,它返回语法错误。 所以,任何解决方案都会有好处,或者如果我错了,请指出。 提前致谢

The SyntaxError is due to https://www.python.org/dev/peps/pep-3127/ — which basically made Python 3 stop silently interpreting 0-prefixed numbers as octal (which is what Python 2 does).

实际上0o111 (即八进制的 111)计算为十进制的 73。

您的问题并没有提供太多关于您正在查看的长度以及您需要如何处理的信息。 但是,如果您想知道一个数字由多少个十进制数字组成,您可以执行以下操作:

len(int(number_as_string, 10))

这将确保即使'0111'也被解释为十进制(即 111)。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM