简体   繁体   中英

Length of an integer with leading zeros in python

How to find length of an integer. There are many solutions for that, I have used (int(math.log10(TheNumber))+1) . But if the number is '0111', it returns as '1' in python 2.7 and in python 3.* it returns 'SyntaxError: leading zeroes in a decimal number is not permitted' . But '0111' is '111'. But using len(str(number)) is giving the correct length. Any solutions for this..

Just want to have an clarification about this. Thanks in advance

Sorry for little information in the question. The question is, 0111,length of this number is 3, but when I check the length of this integer, in python 2.7,it return 2. Code is

a = 0111

print(len(str(a)))

it returns 2 as the answer, when I run the above same code in python3.* it shows as 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 .

In my program, if user gives this kind of number,ie numbers which has leading zeroes, how should I convert it into a number which has no leading zeroes in it.

my_input = 0111

converted_input =111

In python 2.7 it is considered as Octal number, when I print it, it returns 73 In python 3.* it is asking for Octal representation(SyntaxError). If I use another method int(math.log10(TheNumber))+1

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

In python 2.7 it returns 2,converts into octal number implicitly. In python 3.* it return Syntax Error. So,any solutions for this will do good or If I am wrong, please point out. Thanks in advance

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).

And indeed 0o111 (that is, 111 in octal) evaluates to 73 in decimal.

Your question doesn't give much information of what kind of length you're looking at — and what you need to do with it. But if you want to know how many decimal digits a number is composed of, you can do something like:

len(int(number_as_string, 10))

This will make sure that even '0111' is interpreted in decimal (that is, 111).

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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