如何获取整数的长度。有许多解决方案,我使用了
抱歉问题中信息较少。 问题是: 0111 ,这个数字的长度是3,但是当我检查这个整数的长度时,在 Python 2.7中返回2。 代码为:
(int(math.log10(TheNumber))+1)
。但是如果数字是 '0111',它在 python 2.7 中返回 '1',在 python 3.* 中返回 'SyntaxError: leading zeroes in a decimal number is not permitted'
。但 '0111' 实际上是 '111'。但是使用 len(str(number))
可以得到正确的长度。是否有其他解决方案?希望能够得到澄清,谢谢。抱歉问题中信息较少。 问题是: 0111 ,这个数字的长度是3,但是当我检查这个整数的长度时,在 Python 2.7中返回2。 代码为:
a = 0111
print(len(str(a)))
当我在Python3.*中运行上述相同代码时,它显示为“SyntaxError: leading zeros in decimal integer literals are not permitted; use an 0o prefix for octal integers
”,但在Python2.7中返回答案2。
如果用户提供这种具有前导零的数字,应如何将其转换为没有前导零的数字。
例如:my_input = 0111,转换后的结果为:converted_input = 111。
在Python2.7中,该数字被视为八进制数,并返回“73
”;而在Python3.*中,则要求以八进制表示(SyntaxError)。如果使用另一种方法:int(math.log10(TheNumber))+1
。
import math
a = 0111
print(int(math.log10(a))+1)
在 Python 2.7 中,它返回 2,并隐式地转换为八进制数字。 在 Python 3.* 中,它会返回语法错误。因此,任何解决方案都可以做得很好,如果我错了,请指出。提前致谢。
len(number)
即可。 - Mark