Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Split a string after a set of specific words in Python

I want to split a string "Kushak Road Main Road Teen Murti Marg X Area" after given set of words like ['path', 'marg', 'road', 'rd']such that I will get an output like ['Kushak Road', 'Main Road', 'Teen Murti Marg']. The words in the list are case insensitive.

I tried following:

re.split(r"\broad|marg\b", "Kushak Road Main Road Teen Murti Marg X Area", flags = re.IGNORECASE)

Output:

['Kushak ', ' Main ', ' Teen Murti ', ' X Area']

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

I would not use split for this, but instead findall, looking for strings that start with a non-whitespace character and finish with road or marg:

re.findall(r'\S.*?\b(?:road|marg)\b', "Kushak Road Main Road Teen Murti Marg X Area", re.I)

Output:

['Kushak Road', 'Main Road', 'Teen Murti Marg']
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading