从字符串中提取数字到lis中

2024-06-28 20:55:04 发布

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

我想把字符串中的数字提取到一个列表中,但也要包括其他字母。在

例如:

a='a815e8ef951'

结果应该是:

^{pr2}$

谢谢!在


Tags: 字符串列表字母数字pr2a815e8ef951
2条回答

您可以使用正则表达式和re来执行此操作:

import re
matches = re.findall(r'(\d+|\D+)', 'a815e8ef951')
matches = [ int(x) if x.isdigit() else x for x in matches ]
# Output: ['a', 815, 'e', 8, 'ef', 951]

您主要将itertools.groupby列表理解表达式一起使用:

>>> from itertools import groupby, chain
>>> a='a815e8ef951'

>>> [''.join(s) for _, s in groupby(a, str.isalpha)]
['a', '815', 'e', '8', 'ef', '951']

如果还想将整型字符串转换为int,则必须将表达式修改为:

^{pr2}$

为了使最后一个表达式更简洁,可以将if部分移动到某个函数中,如下所示:

def tranform_string(to_int, my_list):
    my_string = ''.join(my_list)
    return int(my_string) if to_int else my_string

new_list = [tranform_string(i, s) for i, s in groupby(a, str.isdigit)]
#                                       using `isdigit()` here  ^

其中new_list将保存所需的内容。在

相关问题 更多 >