从中删除空字符串关于芬德尔命令

2024-05-08 16:43:47 发布

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

import re
name = 'propane'
a = []
Alkane = re.findall('(\d+\W+)*(methyl|ethyl|propyl|butyl)*(meth|eth|prop|but|pent|hex)(ane)', name)
if Alkane != a:
    print(Alkane)

正如你所看到的,当普通快车吸收丙烷时,它将输出两个空字符串。在

^{pr2}$

对于这些类型的输入,我想从输出中删除空字符串。我不知道这个输出是什么形式的,它看起来不像一个常规的列表。在


Tags: 字符串nameimportrebutethpropmeth
3条回答

可以使用str.split()str.join()从输出中删除空字符串:

>>> import re
>>> name = 'propane'
>>> Alkane = re.findall('(\d+\W+)*(methyl|ethyl|propyl|butyl)*(meth|eth|prop|but|pent|hex)(ane)', name)
>>> Alkane
[('', '', 'prop', 'ane')]
>>> [tuple(' '.join(x).split()) for x in Alkane]
[('prop', 'ane')]

或使用filter()

^{pr2}$

doc中声明包含空匹配。在

If one or more groups are present in the pattern, return a list of groups; this will be a list of tuples if the pattern has more than one group. Empty matches are included in the result.

这意味着你需要自己过滤掉空的化合物。使用空字符串的错误。在

import re
name = 'propane'
alkanes = re.findall(r'(\d+\W+)*(methyl|ethyl|propyl|butyl)*(meth|eth|prop|but|pent|hex)(ane)', name)

alkanes = [tuple(comp for comp in a if comp) for a in alkanes]

print(alkanes) # [('prop', 'ane')]

另外,避免使用大写的变量名,因为它们通常是为类名保留的。在

您可以使用filter删除空字符串:

import re
name = 'propane'
a = []
Alkane = list(map(lambda m: tuple(filter(bool, m)), re.findall('(\d+\W+)*(methyl|ethyl|propyl|butyl)*(meth|eth|prop|but|pent|hex)(ane)', name)))
if Alkane != a:
    print(Alkane)

或者您可以使用列表/元组理解:

^{pr2}$

两种输出:

[('prop', 'ane')]

相关问题 更多 >