如何在字符串中间抓取数字?(Python)

2024-10-05 10:56:29 发布

您现在位置:Python中文网/ 问答频道 /正文

random string
this is 34 the string 3 that, i need 234
random string
random string
random string
random string

random string
this is 1 the string 34 that, i need 22
random string
random string
random string
random string

random string
this is 35 the string 55 that, i need 12
random string
random string
random string
random string

在一个字符串中有多行。其中一行是重复的,但每次都有不同的数字。我在想怎么把这些行里的数字存储起来。这些数字将始终位于行中的相同位置,但可以是任意位数。在

编辑:随机字符串中也可以有数字。在


Tags: the字符串编辑stringthatis数字random
3条回答

使用正则表达式:

>>> import re
>>> comp_re = re.compile('this is (\d+) the string (\d+) that, i need (\d+)')
>>> s = """random string
this is 34 the string 3 that, i need 234
random string
random string
random string
random string

random string
this is 1 the string 34 that, i need 22
random string
random string
random string
random string

random string
this is 35 the string 55 that, i need 12
random string
random string
random string
random string
"""
>>> comp_re.findall(s)
[('34', '3', '234'), ('1', '34', '22'), ('35', '55', '12')]

假设s是整个多行字符串,可以使用如下代码

my_list = []
for line in s.splitlines():
    ints = filter(str.isdigit, line.split())
    if ints:
          my_list.append(map(int, ints))

这将为您提供一个列表列表,每行包含整数的一个整数列表。如果您想要所有数字的单一列表,请使用

^{pr2}$

通过使用正则表达式

import re
s = """random string
this is 34 the string 3 that, i need 234
random string
random string
random string
"""
re.findall('this is (\d+) the string (\d+) that, i need (\d+)', s)    

相关问题 更多 >

    热门问题