If I have a string and I want to split it at '.' which is not contained within brackets, how would I do it.
'(1.2).(2.1)'
to get ['(1.2)', '(2.1)']
'(1.2).2'
to get ['(1.2)', '2']
'1.(1.2)'
to get ['1', '(1.2)']
The current write index on a data stream cannot be split.
Split is used to break a delimited string into substrings. You can use either a character array or a string array to specify zero or more delimiting characters or strings. If no delimiting characters are specified, the string is split at white-space characters.
To get the index of a character in a string, you use the indexOf() method, passing it the specific character as a parameter. This method returns the index of the first occurrence of the character or -1 if the character is not found.
This program assumes that the input will be valid always, though it is fairly easy to include conditions to handle it properly.
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']
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With