python---字符串转int型

class Solution:
    def AutoStrToInt(self,s):
        s=s.lstrip()
        if not s:
            return 0
        sign=""
        if s[0] in ["+","-"]:
            sign=s[0]
            s=s[1:]
        result=[]
        try:
            for c in s:
                int(c)
                result.append(c)
        except:
            pass
        if not result:
            return 0
        result=int('{}{}'.format(sign,"".join(result)))
        if result<=pow(-2,31):
            return pow(-2,31)
        elif result>=pow(2,31)-1:
            return pow(2,31)-1
        return result
su=Solution()
print(su.AutoStrToInt("-222"))

int类型的范围-2^31 到
2^31-1

猜你喜欢

转载自blog.csdn.net/haoshan4783/article/details/89207476