无法在Python中将字符串转换为int

2024-10-02 12:32:44 发布

您现在位置:Python中文网/ 问答频道 /正文

这个python片段有什么问题:

for zhszam in pontok.keys():
    s = 0
    for p in pontok[zhszam]:
        if p.isdigit():
            s += int(p)
            print s
    pontok[zhszam] = s
return pontok

其中pontok{1: ['10', ' 5', ' 3', ' 10', ' 7'], 2: ['10', ' 5', ' 3', ' 10']}。 它以某种方式给出了以下错误的输出:

^{pr2}$

而值应该是数字的总和。在

提前谢谢!在


Tags: inforreturnif错误方式数字keys
3条回答

我宁愿发表评论,也不愿留下这个作为答案,但我还没有代表。这个问题将帮助您剥离那些前导空格:Python remove all whitespace in a string

除了第一个'10'之外,每个字符串都有一个前导空格,而不是数字。所以根本就没有被处理。在

尝试:

for p in pontok[zhszam]:
    p = p.strip()
    # ...

您不应该使用str.isdigit,它很容易损坏。最好使用带有int()的try except块。在

>>> dic = {1: ['10', ' 5', ' 3', ' 10', ' 7'], 2: ['10', ' 5', ' 3', ' 10']}
for k,v in dic.iteritems():
    s = 0
    for x in v:
        try:
            s += int(x)     #raises Error if the item is not a valid number
        except:              
            pass            #leave the item as it is if an error was thrown
    dic[k] = s 
...     
>>> dic
{1: 35, 2: 28}

相关问题 更多 >

    热门问题