[英]`int('10**2')` raises `ValueError: invalid literal for int() with base 10: '10**2'` despite `type(10**2)` being `<class 'int'>`
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'>
。
I take input n
as n = input()
, then I do int(n)
.我将输入
n
作为n = input()
,然后我做int(n)
。 When I input 10**2
, I get ValueError: invalid literal for int() with base 10: '10**2'
.当我输入
10**2
时,我得到ValueError: invalid literal for int() with base 10: '10**2'
。
I'm guessing the issue is that 10**2
is not a literal - it has to be evaluated first, but I'm hesitant to do int(eval(n))
since n
can be any string.我猜问题是
10**2
不是文字 - 它必须首先被评估,但我犹豫是否执行int(eval(n))
因为n
可以是任何字符串。
By contrast, float('1e2')
despite being very similar, doesn't raise an error.相比之下,
float('1e2')
尽管非常相似,但不会引发错误。 I guess 1e2
is considered a literal...?我猜
1e2
被认为是文字......? and doesn't have to be evaluated?并且不需要评估?
My current workaround is to check whether the string contains '**'
and if it does, handle it accordingly:我当前的解决方法是检查字符串是否包含
'**'
,如果包含,则进行相应处理:
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)
or to support expressions like 3**3**3
:或者支持像
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)
Yes, 10**2
must be evaluated while 1e2
is a constant.是的,必须评估
10**2
而1e2
是常数。 I suggest taking a look at Evaluating a mathematical expression in a string for some options regarding parsing mathematical expressions in strings.我建议看一下Evaluating a mathematical expression in a string以了解有关解析字符串中的数学表达式的一些选项。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.