【问题标题】:How to interpret numbers with leading zero's as decimal?如何将前导零的数字解释为十进制?
【发布时间】:2019-10-02 11:10:13
【问题描述】:

全部! 我需要将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

【问题讨论】:

  • 为什么需要这个?以 0 开头的数字文字应该是八进制。
  • for 65 正在打印 101 对你来说是错误的,那么正确的答案是什么。不知道你需要什么?
  • print(oct(65)) 应该生产什么?
  • 脚本中的值是文字吗?或者是用户输入数据,例如使用raw_input?还是从文件中读取?我不确定我是否理解您所说的问题是如何解决的。

标签: decimal python-2.x octal


【解决方案1】:

这是 Python2 的正常行为。这种号码是specified in the language

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

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

如果你想把077解释成77,你最多只能做一些丑陋的转换:

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

【讨论】:

  • 是的,但如果可能的话,我需要改变这种行为,我需要返回给我用户的相同数字
  • 这就是 Python2 的工作原理。除非你重写 Python 解释器的部分,否则这是不可能的。
【解决方案2】:

你能把它转换成字符串吗?

例如:

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

【讨论】:

猜你喜欢
  • 2021-12-25
  • 1970-01-01
  • 1970-01-01
  • 2014-03-21
  • 1970-01-01
  • 2013-04-01
  • 1970-01-01
相关资源
最近更新 更多