logo

Concatenating Strings in Julia 📂Julia

Concatenating Strings in Julia

Code

Concatenate Strings *

julia> "oh" * "my" * "girl"
"ohmygirl"

Corresponds to the + in Python.

Concatenate Multiple Strings string()

julia> string("oh","my", "girl")
"ohmygirl"

Corresponds to paste0() in R.

Joining Items of a List of Strings join()

julia> OMG = ["oh","my", "girl"]
3-element Vector{String}:
 "oh"
 "my"
 "girl"

julia> join(OMG)
"ohmygirl"

Corresponds to join() in Python.

Repeat the Same String ^

julia> "=-" ^ 10
"=-=-=-=-=-=-=-=-=-=-"

Corresponds to * in Python. The expression of repetition as exponentiation is no coincidence, as in Python, the binary operation for connecting strings is +(sum), and repeating it is *(product). Similarly, in Julia, the operation for connecting strings is *(product), and repeating it becomes ^(exponent).

Why?

Why not use +, which is more intuitive and easy to understand as in other languages? It’s because, from an algebraic, mathematical perspective, merging strings is closer to multiplication than addition and is more natural1. It would be best if you could understand what a Free group in Algebra means, but even without such background knowledge, the representation of the product of x and y as x * y = xy in mathematics is acceptable. $$ x \ast y = xy $$ Now consider appending the string "litol" to "xy", creating "xylitol". $$ xy \ast litol = xylitol $$ It makes sense. Thinking about "xy" + "litol" now might feel a bit strange. The people who made Julia are seriously committed to such mathematical intuition.

Environment

  • OS: Windows
  • julia: v1.6.2