int的文字无效

时间:2014-01-21 07:45:48

标签: python int

我有一个功能:

import urllib2
import json
id = u'asadasd58'
if not id.isdigit:
    url = 'http://api.steampowered.com/ISteamUser/ResolveVanityURL/v0001/?key='+SteamKey+'&vanityurl='+id
    file = urllib2.urlopen(url).read()
    file = json.loads(file, 'utf-8')
    if file['response']['success'] == 1:
        print file['response']['steamid']
    else:
        print 0
else:
    print int(id)

它应该像这样工作:如果提供64位SteamID(或只是一个数字),它只是打印。如果它不仅仅是一个数字,我们试着得到它是否是虚荣网址,并解析真正的64位id,如果我们无法解决(文件['response'] ['success'] == 42)然后我们返回但是当你提供上面的id时,它会尝试对它进行int,即使它不是数字。为什么呢?

Traceback (most recent call last): File "test.py", line 13, in <module> print int(id) ValueError: invalid literal for int() with base 10: 'asadasd58' 

1 个答案:

答案 0 :(得分:5)

我不知道你的全部追溯,但是......

id = u'asadasd58'
if not id.isdigit():  # call this function! with real parentheses!
    ...
else:
    print int(id)     # this will fail!