赞
踩
给定一个字符串,可能包含空格、字母等转化为数字,或者逆序输出数字
下面是具体实现:
#!usr/bin/env python
#encoding:utf-8
'''
__Author__:沂水寒城
功能:将字符串转化为数字
'''
def trans_str2_num(one_str):
'''
'''
sigmod=1
one_str=one_str.strip()
if not one_str:
return 0
if one_str[0]=='-':
sigmod=-1
one_str=one_str[1:]
elif one_str[0]=='+':
one_str=one_str[1:]
else:
pass
one_str_list=list(one_str)
for i in range(len(one_str_list)):
if not one_str_list[i].isdigit():
one_str_list=one_str_list[:i]
break
res=0
#想逆序输出的话可以使用
# for one in one_str_list[::-1]:
for one in one_str_list:
res+=ord(one)-ord('0')
res*=10
res/=10
res*=sigmod
if res>2147483647:
return 2147483647
elif res<-2147483647:
return -2147483647
else:
return res
if __name__ == '__main__':
one_str_list=['',' ','-123j442','2389083','hjsdhvj','21474836479','-21474836479']
for one_str in one_str_list:
print one_str+'---->'+str(trans_str2_num(one_str))
结果如下:
---->0
---->0
-123j442---->-123
2389083---->2389083
hjsdhvj---->0
21474836479---->2147483647
-21474836479---->-2147483647
[Finished in 0.7s]
Copyright © 2003-2013 www.wpsshop.cn 版权所有,并保留所有权利。