Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python 3: Split string under certain condition

I have difficulties splitting a string into specific parts in Python 3. The string is basically a list with a colon (:) as a delimiter.

Only when the colon (:) is prefixed with a backslash (\), it does not count as a delimiter but part of the list item.

Example:

String --> I:would:like:to:find\:out:how:this\:works

Converted List --> ['I', 'would', 'like', 'to', 'find\:out', 'how', 'this\:works']

Any idea how this could work?

@Bertrand I was trying to give you some code and I was able to figure out a workaround but this is probably not the most beautiful solution

text = "I:would:like:to:find\:out:how:this\:works"

values = text.split(":")
new = []
concat = False
temp = None

for element in values:

    # when one element ends with \\

    if element.endswith("\\"):
        temp = element
        concat = True

    # when the following element ends with  \\ 
    # concatenate both before appending them to new list

    elif element.endswith("\\") and temp is not None:
        temp = temp + ":" + element
        concat = True

   # when the following element does not end with \\
   # append and set concat to False and temp to None

    elif concat is True:
        new.append(temp + ":" + element)
        concat = False
        temp = None

   # Append element to new list

    else:
        new.append(element)

print(new)

Output:

['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']
like image 440
Melvin Avatar asked Dec 19 '25 12:12

Melvin


1 Answers

You should use re.split and perform a negative lookbehind to check for the backslash character.

import re
pattern = r'(?<!\\):'
s = 'I:would:like:to:find\:out:how:this\:works'
print(re.split(pattern, s))

Output:

['I', 'would', 'like', 'to', 'find\\:out', 'how', 'this\\:works']
like image 171
Jim Wright Avatar answered Dec 22 '25 01:12

Jim Wright



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!