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

Pulling out certain strings from split method

I would like my output to be only words in parentheses inside the string without using regex.

Code:

def parentheses(s):
    return s.split()

print(parentheses("Inside a (space?)")) 
print(parentheses("To see (here) but color")) 
print(parentheses("Very ( good (code")) 

Output:

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

['Inside', 'a', '(space?)'] -> **space?**
['To', 'see', '(here)', 'but', 'color'] -> **here**
['Very', '(', 'good', '(code'] -> **empty**

>Solution :

Here is an old fashioned way of doing it with a loop and referencing the ends with a dictionary.

def parentheses(s):
    ends = {"(":[],")":[]}
    for i, char in enumerate(s):
        if char in ["(", ")"]:
            ends[char].append(i)
    if not ends["("] or not ends[")"]:
        return ""
    return s[min(ends["("]) + 1: max(ends[")"])]


print(parentheses("Inside a (space?)"))
print(parentheses("To see (here) but color"))
print(parentheses("Very ( good (code"))

OUTPUT:

space?
here

If you must use str.split this will work as well.

def parentheses(s):
    parts = s.split("(")
    if len(parts) > 1:
        s = "(".join(parts[1:])
        parts = s.split(")")
        if len(parts) > 1:
            return ")".join(parts[:-1])
    return ""
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