如何利用python提取字符串中的数字

作者:__泡泡茶壶 时间:2022-12-09 10:32:13 

一、isdigit()函数

isdigit()函数是检测输入字符串是否只由数字组成。如果字符串只包含数字则返回 True 否则返回 False。

dream = "123456"
print(dream.isdigit())
# 返回:True

dream = "123abc456"
print(dream.isdigit())
# 返回:False

dream = 'abcd'
print(dream.isdigit())
# 返回: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 math
def is_sqr(x):
   return math.sqrt(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 n

print(list(filter(isprimer, L)))

5、去除空格和空值

def not_empty(s):
 return s and s.strip()

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_)    # 123334
a = "".join(list(filter(str.isdigit, '123ab45')))
print(a)
# 返回12345

b = list(filter(str.isdigit, '123ab45'))
print(b)
# 返回['1', '2', '3', '4', '5']
time_ = "2019年09月04日 11:00"
time_filter = filter(str.isdigit, time_)

print(time_filter)           # <filter object at 0x0000019358731BE0>
print(type(time_filter))     # <class 'filter'>
time_list = list(time_filter)       # ['2', '0', '1', '9', '0', '9', '0', '4', '1', '1', '0', '0']
time_str = "".join(time_list)       # 转为str    201909041100
time_int = int(time_str)            # 转为int    201909041100

利用正则表达式

import re
str_ = "12今天333天气4不错"
number = re.findall("\d+",str_)    # 输出结果为列表
print(number)

# 输出结果:['12', '333', '4']

四、匹配指定字符串开头的数字

例如下面的string:

tensorflow:Final best valid 0 loss=0.20478513836860657 norm_loss=0.767241849151384 roc=0.8262403011322021 pr=0.39401692152023315 calibration=0.9863265752792358 rate=0.0

提取 calibration=0.9863265752792358 .

# 匹配“calibration=”后面的数字
pattern = re.compile(r'(?<=calibration=)\d+\.?\d*')
pattern.findall(string)

# ['0.9863265752792358']

如何利用python提取字符串中的数字

五、匹配时间,17:35:24

string = "WARNING:tensorflow: 20181011 15:28:39 Initialize training"
pattern = re.compile(r'\d{2}:\d{2}:\d{2}')
pattern.findall(string)
# ['15:28:39']

六、匹配时间,20181011 15:28:39

string = "WARNING:tensorflow: 20181011 15:28:39 Initialize training"
pattern = re.compile(r'\d{4}\d{2}\d{2}\s\d{2}:\d{2}:\d{2}')
pattern.findall(string)
# ['20181011 15:28:39']

来源:https://blog.csdn.net/luoxuexi2020/article/details/116666167

标签:python,字符串,数字
0
投稿

猜你喜欢

  • Python配置文件管理之ini和yaml文件读取的实现

    2022-01-10 15:33:08
  • 随机6+1选号码摇奖程序

    2008-07-18 13:15:00
  • GoLang使goroutine停止的五种方法实例

    2023-09-02 08:31:33
  • python实现决策树分类

    2021-04-04 13:35:28
  • php fopen()函数案例详解

    2023-07-16 22:21:26
  • python编写暴力破解FTP密码小工具

    2021-11-29 15:32:40
  • pandas ix &iloc &loc的区别

    2023-03-12 16:31:54
  • go语言LeetCode题解720词典中最长的单词

    2023-08-05 19:46:04
  • python实现简易版学生成绩管理系统

    2022-01-19 10:52:03
  • 浅谈Django 页面缓存的cache_key是如何生成的

    2022-03-20 09:53:02
  • Dhtml网页实例教程

    2007-10-09 13:39:00
  • Django中create和save方法的不同

    2021-06-16 14:24:02
  • 详解Go语言中关于包导入必学的 8 个知识点

    2023-07-09 05:38:11
  • python技巧分享Excel创建和修改

    2022-01-09 12:04:59
  • 利用Python找出删除自己微信的好友并将他们自动化删除

    2022-05-23 00:10:13
  • Python+腾讯云服务器实现每日自动健康打卡

    2023-08-18 00:22:44
  • tensorflow识别自己手写数字

    2022-10-12 20:25:04
  • python字符串的多行输出的实例详解

    2021-06-25 20:59:45
  • Pandas使用Merge与Join和Concat分别进行合并数据效率对比分析

    2023-03-13 12:14:01
  • Python将py文件编译为exe文件

    2023-07-29 10:05:36
  • asp之家 网络编程 m.aspxhome.com