Home > Enterprise >  Pulling out certain strings from split method
Pulling out certain strings from split method

Time:08-09

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**

CodePudding user response:

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 ""
  • Related