Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

split a string at a certain index

Tags:

python

split

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)']

like image 315
user2989280 Avatar asked Mar 19 '14 13:03

user2989280


People also ask

Can we use index in Split?

The current write index on a data stream cannot be split.

How do you split part of a string?

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.

How do you get a specific index of a string in JavaScript?

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.


1 Answers

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']
like image 158
thefourtheye Avatar answered Oct 20 '22 01:10

thefourtheye