Split and rsplit strings?

Hello,

how can i combine that in one (CostumNode)…

strings = IN[0]
sep = IN[1]
depth = IN[2]

OUT = strings.split(sep,depth)

or

strings = IN[0]
sep = IN[1]
depth = IN[2]

OUT = strings.rsplit(sep,depth)

how can i combine that… one idea is via a function and a boolen, so the user can deside how to access the string… ? it works well for single value… any idea for comprehansions :slight_smile:

strings = IN[0]
sep = IN[1]
switch = IN[2]
depth = IN[3]



OUT = []

def switchsplit(x):
    if switch == True:
        return x.split(sep,depth)
    else:
        switch == False
        return x.rsplit(sep,depth)
        
OUT = switchsplit(strings)

strings = IN[0]
sep = IN[1]
switch = IN[2]
depth = IN[3]



OUT = []

def switchsplit(x):
    if switch == True:
        return x.split(sep,depth)
    else:
        switch == False
        return x.rsplit(sep,depth)

for i in strings:
    OUT.append(switchsplit(i))

I sloved it look:

strings = IN[0]
sep = IN[1]
switch = IN[2]
depth = IN[3]

if isinstance(strings,list):
    strings = IN[0]
else:
    strings = [IN[0]]

OUT = []

def switchsplit(x):
    if switch == True:
        return x.split(sep,depth)
    else:
        switch == False
        return x.rsplit(sep,depth)

for i in strings:
    OUT.append(switchsplit(i))

finaly i can ask about some comprehansion sytle ? it works well

List comprehension is a good thing to learn about. We covered it briefly in the Dynamo Office Hour last winter, but this is my favorite source for learning it: All About Python List Comprehension | by Baijayanta Roy | Towards Data Science

I haven’t tried any of the code below as I’m not at my work computer at the moment, but below should get you started (less any formatting typos and such).

The key is to start with defining your output as a list.
OUT = []
Then inside of the list, apply what you want to do on a single variable.
OUT = [ x.split(sep,depth) ]
Then define where that single variable comes from.
OUT = [ x.split(sep,depth) for x in strings ]

From there we can move into the other diretion (yes, I am defining OUT twice here… it’ll make sense soon).
OUT = [ x.rsplit(sep,depth) for x in strings ]

And finally we define an if statement to decide which section of code to run.

if switch:
    OUT = [ x.rsplit(sep,depth) for x in strings ]
else:
    OUT = [ x.split(sep,depth) for x in strings ]

Combining it all together, we get:

strings = IN[0]
sep = IN[1]
switch = IN[2]
depth = IN[3]
if switch:
    OUT = [ x.rsplit(sep,depth) for x in strings ]
else:
    OUT = [ x.split(sep,depth) for x in strings ]
1 Like