Python 字符串转整数:高效代码实现与解析
def str_to_int(s):
# 判断字符串是否为空
if not s:
return 0
# 判断字符串是否有正负号,记录符号位
sign = 1
if s[0] == '-':
sign = -1
s = s[1:]
elif s[0] == '+':
s = s[1:]
# 判断字符串是否只包含数字
for ch in s:
if ch < '0' or ch > '9':
return 0
# 转化为整数并乘以符号位
res = 0
for ch in s:
res = res * 10 + ord(ch) - ord('0')
return res * sign
该代码首先判断字符串是否为空,然后判断字符串是否有正负号,记录符号位。接着判断字符串是否只包含数字,如果不是则返回0。最后将字符串转化为整数并乘以符号位返回。
原文地址: https://www.cveoy.top/t/topic/okyH 著作权归作者所有。请勿转载和采集!