繁体   English   中英

`int('10**2')` 引发`ValueError: invalid literal for int() with base 10: '10**2'` 尽管`type(10**2)` 是`<class 'int'> `</class>

[英]`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' despite type(10**2) being <class 'int'>

我将输入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)

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

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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