【问题标题】:`int('10**2')` raises `ValueError: invalid literal for int() with base 10: '10**2'` despite `type(10**2)` being `<class 'int'>``int(\'10**2\')` 引发 `ValueError: invalid literal for int() with base 10: \'10**2\'` 尽管 `type(10**2)` 是 `<class \'int\'>`
【发布时间】:2022-11-25 11:15:54
【问题描述】:

int('10**2') 提出 ValueError: invalid literal for int() with base 10: '10**2' 尽管 type(10**2)&lt;class 'int'&gt;

我将输入n作为n = input(),然后我做int(n)。当我输入10**2时,我得到ValueError: invalid literal for int() with base 10: '10**2'

我猜问题是 10**2 不是文字 - 它必须首先被评估,但我犹豫要不要做 int(eval(n)) 因为 n 可以是任何字符串。


相比之下,float('1e2') 尽管非常相似,但不会引发错误。我猜 1e2 被认为是文字......?并且不需要评估?


我目前的解决方法是检查字符串是否包含'**',如果包含,则进行相应处理:

n = input()
if '**' in n:
  base, exp, *a = n.split('**')
  if a:
    raise ValueError(f'This input, {n}, can't be interpreted as an integer')
  n = int(base)**int(exp)
else:
  n = int(n)

或者支持像3**3**3这样的表达式:

n = input()
if '**' in n:
  operands = input.split('**')
  # '**' associates to the right
  exp = 1
  while operands:
    base = int(operands.pop())
    exp = base ** exp
  n = exp
else:
  n = int(n)

【问题讨论】:

    标签: python input integer user-input literals


    【解决方案1】:

    是的,必须评估 10**21e2 是常量。我建议查看Evaluating a mathematical expression in a string,了解有关解析字符串中的数学表达式的一些选项。

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-12-25
      • 2022-01-09
      • 2019-04-16
      • 2018-02-01
      • 1970-01-01
      • 1970-01-01
      • 2021-08-11
      • 2020-08-02
      相关资源
      最近更新 更多