首页 > 代码库 > Python之str型转成int型

Python之str型转成int型

str转int:

1 def fn(x,y):
2     return x*10+y
3 
4 def char2num(s):
5     return {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9}[s]  # 特别注意这里,后面还有个 [s]
6 
7 print(type(reduce(fn, map(char2num, 1738785))))
8 print(reduce(fn, map(char2num, 1738785)))

输出如下:

1 <type int>
2 1738785

整理成一个 str2int 函数就是如下喽:

 1 from functools import reduce
 2 
 3 def str2int(s):
 4     def fn(x,y):
 5         return x*10+y
 6     def char2num(s):
 7         return {0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9}[s]
 8     return reduce(fn,map(char2num,s))
 9 
10 print(str2int(365779))
11 print(type(str2int(365779)))

 

用匿名函数lambda再简化一下就成了下面这个样子:

1 def str2int(s):
2     return reduce(lambda x,y:x*10+y, map(lambda s:{0:0, 1:1, 2:2, 3:3, 4:4, 5:5, 6:6, 7:7, 8:8, 9:9}[s], s))

WOC,就一行代码哦,够简单!

 

Python之str型转成int型