2023年6月29日发(作者:)
如何利⽤python提取字符串中的数字⽬录⼀、isdigit()函数⼆、filter() 函数三、提取⼀段字符串中的数字四、匹配指定字符串开头的数字五、匹配时间,17:35:24六、匹配时间,20181011 15:28:39总结⼀、isdigit()函数isdigit()函数是检测输⼊字符串是否只由数字组成。如果字符串只包含数字则返回 True 否则返回 False。dream = "123456"print(t())# 返回:Truedream = "123abc456"print(t())# 返回:Falsedream = 'abcd'print(t())# 返回:False⼆、filter() 函数说明:filter() 函数⽤于过滤序列,过滤掉不符合条件的元素,返回⼀个迭代器对象;如果要转换为列表,可以使⽤ list() 来转换。该接收两个参数,第⼀个为函数,第⼆个为序列,序列的每个元素作为参数传递给函数进⾏判断,然后返回 True 或 False,最后将返回 True 的元素放到新列表中。语法:filter(function, iterable)1、过滤出列表中的所有奇数:def is_odd(n): return n % 2 == 1
tmplist = filter(is_odd, [1, 2, 3, 4, 5, 6, 7, 8, 9, 10])newlist = list(tmplist)print(newlist)2、过滤出列表中的所有偶数:l = [x for x in range(10)]print(list(filter(lambda x : x%2 == 0, l)))3、过滤出1~100中平⽅根是整数的数:import mathdef is_sqr(x): return (x) % 1 == 0
tmplist = filter(is_sqr, range(1, 101))newlist = list(tmplist)print(newlist)4、删除1-100中素数L = range(1, 101)def isprimer(n): flag = 1 for i in range(2, n): if n % i == 0: flag = 0 if flag == 0: return nprint(list(filter(isprimer, L)))5、去除空格和空值def not_empty(s): return s and ()filter(not_empty, ['A', '', 'B', None, 'C', ' '])6、⾼阶运⽤def _odd_iter(): n = 1 while True: n = n + 2 yield n
def _not_divisible(n):
return lambda x : x%n>0
def primes(): yield 2 it = _odd_iter() ftr = filter(_not_divisible(2), it) #1 while True: n = next(ftr ) #2 yield n
ftr = filter(_not_divisible(n), ftr ) #3
for n in primes(): if n < 100: print('now:',n) else: break三、提取⼀段字符串中的数字列表转字符串number = ['12', '333', '4']number_ = "".join(number) # 列表转字符串print(number_) # 123334a = "".join(list(filter(t, '123ab45')))print(a)# 返回12345b = list(filter(t, '123ab45'))print(b)# 返回['1', '2', '3', '4', '5']time_ = "2019年09⽉04⽇ 11:00"time_filter = filter(t, time_)print(time_filter) #
发布者:admin,转转请注明出处:http://www.yc00.com/web/1687977107a62819.html
评论列表(0条)