This program assumes that the entry will always be valid, although it is fairly easy to include conditions for proper processing.
def custom_split(data): element, opened, result = "", 0, [] for char in data: # Immediately following if..elif can be shortened like this # opened += (char == ")") - (char == "(") # Wrote like that for readability if char == ")": opened -= 1 elif char == "(": opened += 1 if char == "." and opened == 0 and element != "": result.append(element) element = "" else: element += char if element != "": result.append(element) return result print custom_split('(1.2).(2.1)') print custom_split('(1.2).2') print custom_split('2.2') print custom_split('(2.2)') print custom_split('2')
Output
['(1.2)', '(2.1)'] ['(1.2)', '2'] ['2', '2'] ['(2.2)'] ['2']
source share