题目来源:力扣 https://leetcode-cn.com/problemset/all/
class Solution:
def myAtoi(self, str: str) -> int:
#去掉左边空字符
str=str.lstrip()
#如果字符串为空,返回0
if len(str)==0:
return 0
#设置默认输出为0
last=0
#如果有符号设置起始位置2,其余的为1
if str[0]=='-'or str[0]=='+':
i = 2
else:
i = 1
#直到无法强制转换为整数,跳出循环
while i <= len(str):
try:
last=int(str[:i])
i+=1
except:
break
#判断整数范围
int_max = 2 ** 31 -1
int_min = - 2 ** 31
if last > int_max:
last = int_max
if last < int_min:
last = int_min
return last
'''
#使用正则表达式
'''
^:匹配字符串开头
[\+\-]:代表一个'+'或者'-'
?:前面的字符可选(可以有也可以没有)
\d:一个数字
+:前面一个字符的一个或者多个
*:前面一个字符的0个或多个
'''
return max(min(int(*re.findall('^[\+\-]?\d+', str.lstrip())), 2**31 - 1), -2**31)
正则表达式解法:https://leetcode-cn.com/problems/string-to-integer-atoi/solution/python-1xing-zheng-ze-biao-da-shi-by-knifezhu/
强制int解法:https://leetcode-cn.com/problems/string-to-integer-atoi/solution/python-jie-fa-zhu-ge-qiang-zhuan-int-by-lanlan-bup/