Any significant difference between string, *, and interpolation for concatenation?

I’m writing some training material, and I was wondering if there is any difference between the three methods for concatenation that I should be aware of?

The most easiest way to do it is:

greet = "Hello"
whom = "World"
println("$greet, $whom")

For new comers to Julia, is teaching the string() and * useful?

It seems if you’re putting 2 or 3 strings together using string() and * it shouldn’t be a problem. It may become difficult when you have a lot of variables, and need to piece together strings, punctuation and \n.

1 Like

The interpolation gets rewritten internally as string() so that should be the same. string() will also parse other data types as strings if necessary.

1 Like

If I want to print several variables at the same time, I usually use the long form of println(a, b, c, ...). If I have to build up a really long string from a large number of values in a loop, I usually use an IOBuffer to print into, since that will create the string object itself only when it’s consumed. Because strings are immutable in julia, each application of * has to create a new string and can’t modify existing strings, so for really long string concatenation, an IOBuffer is usally faster. This is advanced though and isn’t particularly helpful in introductory material - *, string and multi-argument println should be fine there.


Possibly. Depends on the focus of the course, and whether they need text manipulation. For simple error messages interpolation should be fine, for delimited joining there is also join.

On the surface using $ looks straightforward, especially when you have to deal with quoting punctuation, and ".\n".

A beginner might want to know why they should learn string() and * when $ looks easier? I’ll admit, I’m not too sure myself, so I was wondering what the difference is between them. Does string() or * provide some functionality that $ doesn’t?

Not really, it’s just different syntax for the same thing. Cf

julia> Meta.@lower "$a $b"
:($(Expr(:thunk, CodeInfo(
    @ none within `top-level scope'
1 ─ %1 = Base.string(a, " ", b)
└──      return %1

Different syntax is occasionally useful — sometimes one alternative is more convenient, sometimes the other. Personally I find $ interpolations quite nice for info/error messages that can be read as a template. Just use whatever you prefer.


For completeness, the * function also calls string internally for concatination, see