October 25, 2019

Dynamo: String Concatenation

This may be basic and blindingly obvious to more experienced Dynamo users, but this is something with which I have struggled for some time, and now that I have finally sorted it out, I wanted to document it here for easy future reference.

The String.Concat node in Dynamo provides an easy way to combine two or more strings into one string.
When each item fed into the stringn inputs is an individual string, all of the strings are combined into one string, and that is the output of the node, as shown in the image above.

I rarely need to combine one set of individual strings, however; I almost always have lists of strings to process. Perhaps there is some deficiency in the way I think, but when I first tried to use the String.Concat node with lists of strings, I was expecting that the the result would be a list of concatenated strings, and that the value at each index in that list would be the concatenation of the strings at that same index in each of the input strings. Unfortunately, that is not what the node does.
As you can see, the result is a list of strings, one for each input, with the strings in each input concatenated together. I was expecting ["abc", "123"], but I got ["a1", "b2", "c3"]. This seems contrary to what it does when single strings are input - at least, it does to me. I found this quite frustrating, and on at least one occasion, wrote a quick Python Script node to do the concatenation the way I wanted it. But that quick Python Script did not allow for varying numbers of input lists of strings (I suppose it could be written to do so, but that would no longer be "quick"). I could not understand why the String.Concat node would not do what I wanted, and could not believe that the way it works is what most users would want, most of the time.

Once I set aside my frustration and started thinking again, it dawned on me that all I needed to do was rearrange my input data to work with the way the String.Concat works, and while that requires a few extra nodes, it is fairly easy to do. (Click on the image below to see it full-size.)
By using the List Create node, I combined my individual lists into one list of lists. The List.Transpose node then transforms that list of lists into another list of lists, in which each sublist has a list of the items from the same index in the original sublists. So each sublist has a list of the strings I want combined into one string, and this can be fed into the String.Concat node to get the desired concatenation. The output of the String.Concat node ends up having the list of concatenated strings nested in a list, so adding a List.Flatten node using the default flatten amount (totally flatten) results in a list of the concatenated strings, which was my desired result.

No comments: