【问题标题】:ValueError: invalid literal for int() with base 10: '' python [closed]ValueError:以 10 为基数的 int() 的无效文字:'' python [关闭]
【发布时间】:2013-12-04 12:41:40
【问题描述】:

ValueError: int() 以 10 为底的无效文字:''

为什么它显示 int() 的错误,实际上来自 cgi 的值是字符串,我将其转换为整数,因为我的可比较部分变量 actual_ans_dict 包含一个整数

res12 = form.getvalue('opt_12', '')
res27 = form.getvalue('opt_27', '')
res20 = form.getvalue('opt_20', '')
res16 = form.getvalue('opt_16', '')
res13 = form.getvalue('opt_13', '')
res19 = form.getvalue('opt_19', '')
res25 = form.getvalue('opt_25', '')

actual_ans_dict = {}
count = 0
b = []
for data in prsnobj.result:
    actual_ans_dict[data[0]] = data[1]

#print actual_ans_dict[12], actual_ans_dict[27], actual_ans_dict[20],     actual_ans_dict[16], actual_ans_dict[13], actual_ans_dict[19], actual_ans_dict[25]

if int(res12) == actual_ans_dict[12]:
    count += 1
if int(res27) == actual_ans_dict[27]:
    count += 1
if int(res20) == actual_ans_dict[20]:
    count += 1
if int(res16) == actual_ans_dict[16]:
    count += 1
if int(res13) == actual_ans_dict[13]:
    count += 1
if int(res19) == actual_ans_dict[19]:
    count += 1
if int(res25) == actual_ans_dict[25]:
    count += 1
if count:
    b.append(count)

if len(b)==0:
    print "Fail"

else:
   print "Marks: ", b

【问题讨论】:

    标签: python cgi


    【解决方案1】:

    问题是因为int 试图将'' 转换为以10 为底的数字,这是不可能的。这就是它失败的原因。如果该值不存在,您将获得默认的''

    form.getvalue('opt_12', '')
    

    而不是使用像这样的哨兵值

    form.getvalue('opt_12', '0')
    

    更好的是,当您从这样的表单中获取它们时,您可以将它们转换为数字

    res12 = int(form.getvalue('opt_12', '0'))
    ...
    ...
    ...
    

    【讨论】:

    • 嗯...那很好...谢谢你,,, :)
    • @user3003685 不客气 :) 如果对您有帮助,请考虑接受此答案
    • 好的...至少需要 5 分钟才能接受...
    猜你喜欢
    • 1970-01-01
    • 2017-12-06
    • 2013-08-04
    • 2023-03-09
    • 1970-01-01
    • 1970-01-01
    • 2011-07-17
    • 1970-01-01
    相关资源
    最近更新 更多