Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Removing empty strings from a re.findall command [duplicate]

Tags:

python

regex

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)

As you can see when the regular express takes in propane it will output two empty strings.

[('', '', 'prop', 'ane')]

For these types of inputs, I want to remove the empty strings from the output. I don't know what kind of form this output is in though, it doesn't look like a regular list.

like image 594
Okeh Avatar asked Sep 19 '25 11:09

Okeh


1 Answers

You can use str.split() and str.join() to remove empty strings from your output:

>>> 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')]

Or using filter():

[tuple(filter(None, x)) for x in Alkane]
like image 130
RoadRunner Avatar answered Sep 22 '25 06:09

RoadRunner