How to replace a string from a list of lists using the string.replace node

Hello there i am fairly new to dynamo.
I am trying to replace a string “m” with a string “LD”.
when i do this using the code block, other strings that are words that contain the letter “m” get replaced with LD how do i avoid this?

How do i strictly replace the string “m” only?
Diagram below
green arrow → Desired
red arrow → Not desired

String.Replace does exactly that: it replaces any instance of the searchFor term with the replaceWith term. Replacing a single character is usually not a good idea because you’ll catch every instance.

You have a few options. Because you’re dealing with only a single instance of a single character, you can just check to see if the string is equal to your term, then replace the whole string. That would avoid any substrings containing the term. Based on your example, it also looks like you’re only looking at the string at sub-index 3. If that’s the case, you can just filter out those values, replace any strings matching your term, and then put the sublist back in place.

1 Like

Hello @driftblade

Maybe this will help you.

2 Likes

Hi, try this in a code block
I have since been careful about my phone

x.Length ==1 && x=="m"?
"LD":
x;

Sincerely
christian.stan

3 Likes

Hi,

a solution (multi list level) with numpy, if input list is homogeny

import sys
import clr

clr.AddReference('Python.Included')
import Python.Included as pyInc
path_py3_lib = pyInc.Installer.EmbeddedPythonHome
sys.path.append(path_py3_lib + r'\Lib')
sys.path.append(path_py3_lib + r'\Lib\site-packages')

import numpy as np

data, search_value, replace_value = IN

array_3d = np.array(data).astype(object)
array_3d[array_3d == search_value] = replace_value

OUT = array_3d.tolist()

or in pure Python (input list need not be homogeneous)

import sys

def convert_value(value):
    global search_value
    global replace_value
    return replace_value if value == search_value else value

def nestedRecursFunc(lst, functoApply):
    newlst = list(lst)[:] # copy input list and convert it (if necessary)
    for idx, elem in enumerate(lst):
        if isinstance(elem, list) and len(elem) > 0:
            newlst[idx] = nestedRecursFunc(lst[idx], functoApply)
        elif isinstance(elem, list) and len(elem) == 0:
            newlst[idx] = []
        else:
            newlst[idx] = convert_value(lst[idx])

    return newlst
    
data, search_value, replace_value = IN 

OUT = nestedRecursFunc(data, convert_value)
3 Likes

wow, I learned another new trick with IN entrants Sincerely
christian.stan

1 Like