注意异常情况(字符串为空,字符串包含错误字符)的检查
正负号等特殊情况的考虑
还有要注意大数——这种情况这里面没有考虑
def string2int(str = '-678'):
if str == None:
return None
str = list(str)
isPositive = None
i = 0
if str[i] == '-':
isPositive = False
i += 1
elif str[i] == '+':
isPositive = True
i += 1
else:
isPositive = True
if i >= len(str):
return None
num = 0
while i < len(str):
try:
num = num*10 + int(str[i])
i += 1
except:
return None
if not isPositive:
num = -num
return num