String to Integer

Python

 1class Solution:
 2    def myAtoi(self, str):
 3        """
 4        :type str: str
 5        :rtype: int
 6        """
 7        str = str.strip()
 8        if str == "":
 9            return 0
10        ans = ""
11        negative = False
12        i = 0
13        if (str[i] == "-" or str[i] == "+") and len(str) == 1:
14            return 0
15        if str[i] == "-":
16            negative = True
17            i += 1
18        if str[i] == "+":
19            i += 1
20        if i > 1:
21            return 0
22        no_whitespace = False
23        while i < len(str) and str[i].isdigit() and not no_whitespace:
24            if no_whitespace:
25                break
26            ans+=str[i]
27            i += 1
28        if ans == "":
29            return 0
30        if negative == True:
31            if (int(ans) * -1) < -2147483648:
32                return -2147483648
33            return (int(ans) * -1)
34        if int(ans) > 2147483647:
35            return 2147483647
36        else:
37            return int(ans)