如何将前导零的数字解释为小数?

时间:2019-05-15 10:26:08

标签: decimal python-2.x octal

全部! 我需要将python中以零开头的数字解释为十进制。 (输入时有数字,而不是字符串!) 使用了Python2,在python3中不再存在此类问题。 我不知道该怎么做。 任何人都可以帮助我!!!

示例:

id = 0101
print id
# will print 65 and I need 101

id = 65
print id
# will print 65 - ok

可能的解决方案:

id = 0101

id = oct(id).lstrip('0')

print id
# will print 101 - ok

id = 65

id = oct(id).lstrip('0')

print id
# will print 101 - wrong, need 65

2 个答案:

答案 0 :(得分:1)

这是Python2的正常行为。这类数字是specified in the language

  

octinteger ::= "0" ("o" | "O") octdigit+ | "0" octdigit+

"0" octdigit+(以"0"开头的数字)在设计上是八进制的。您无法更改此行为。

如果您想将077解释为77,那么您最多可以做的就是像这样的丑陋转换:

int(str(oct(077)).lstrip('0'))

答案 1 :(得分:1)

可以将其转换为字符串吗?

例如:

def func(rawNumber):

   id = str(rawNumber)
   if id[0] == '0':
      res = oct(id).lstrip('0')
   else:
      res = id
   return int(res)

# then use it like this:

print(func(0101)) # will print 101
print(func(65))  # will print 65
相关问题