Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Hierarchical string delimiting not splitting

I am trying to create a function to parse a string based on multiple delimiters, but in a hierarchical format: i.e., try the first delimiter, then the second, then the third, etc.

This question seemingly provides a solution, specifically linking this comment.

# Split the team names, with a hierarchical delimiter
def split_new(inp, delims=['VS', '/ ' ,'/']):
    # https://stackoverflow.com/questions/67574893/python-split-string-by-multiple-delimiters-following-a-hierarchy
    for d in delims:
        result = inp.split(d, maxsplit=1)
        if len(result) == 2: 
            return result
        else:
            return [inp] # If nothing worked, return the input  

test_strs = ['STACK/ OVERFLOW', 'STACK #11/00 VS OVERFLOW', 'STACK/OVERFLOW' ]

for ts in test_strs:
    res = split_new(ts)
    print(res)

"""
Output:
['STACK/ OVERFLOW']
['STACK #11/00 ', ' OVERFLOW']
['STACK/OVERFLOW']

Expected:
['STACK',' OVERFLOW']
['STACK #11/00 ', ' OVERFLOW']
['STACK', 'OVERFLOW']

"""

However, my results are not as expected. What am I missing?

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

>Solution :

Execute the "nothing worked" fallback AFTER trying all delimiters:

for d in delims:
    result = inp.split(d, maxsplit=1)
    if len(result) == 2: 
        return result
return [inp] # If nothing worked, return the input  
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading