Pulling out certain strings from split method

Question:

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:

['Inside', 'a', '(space?)'] -> **space?**
['To', 'see', '(here)', 'but', 'color'] -> **here**
['Very', '(', 'good', '(code'] -> **empty**
Asked By: cnsc.bot

||

Answers:

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 ""
Answered By: Alexander
Categories: questions Tags: , , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.