1

I have written a piece of code which takes a keyword and splits a name using that specific keyword, however as split returns the list, now I want to individually check the elements of the returned list and again split it using a different keyword(if it exists), but this time I dont want another sublist to be returned, rather then the elements should get extended in the same list.

Code below :-

def get_comb_drugs(keyword, name):

    if keyword in name:
        name = name.split(keyword)

    return name

print(get_comb_drugs(", polymer with", "Acetaldehyde, polymer with ammonia and formaldehyde"))

The output I get is:

['Acetaldehyde', ' ammonia and formaldehyde']

however, I want to split 'ammonia and formaldehyde' again using " and " keyword and the exact output I want is:

['Acetaldehyde', ' ammonia', 'formaldehyde']

Guide me in achieving the desired result.

1 Answer 1

1

You can use re.split instead with an alternation pattern:

import re
separators = [', polymer with', ' and ']
re.split('|'.join(separators), 'Acetaldehyde, polymer with ammonia and formaldehyde')

This returns:

['Acetaldehyde', ' ammonia', 'formaldehyde']
Sign up to request clarification or add additional context in comments.

4 Comments

Yep, but I cannot explicitly pass ', polymer with' and other pattern. I have lots of such keywords.
You can join these separators into an alternation pattern with the '|'.join method, as shown in my edited answer.
I get your point, but I need to pass many such keywords which I have in a single function which checks and returns the elements in a single list.
@Rajsxx When I said you can use '|'.join to join the separators I meant the separators as a list, exactly what you say you need. I've edited my answer so that you can see the point more clearly.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.