Imagine you have four strings: a
, b
, c
and d
.
Say you want their concatenation, e = a + b + c + d
. However, the +
operator is only defined for two operands, so you would apparently need to concatenate the individual strings one by one.
The naive way to calculate this might be the following:
e = ((a + b) + c) + d
But this is inefficient, because it generates two throwaway strings: a + b
and a + b + c
.
Now, imagine we created a buffer-like object holding all the characters we wanted to combine:
e_buffer = [a, b, c, d]
We could create e
from this all at once, avoiding the need to create many intermediate strings.
This requires a function, which, in Python, we call join
; it is a method of a str
, and intersperses that string between the arguments provided. Therefore, when you execute some_separator.join([a, b, c])
, you get, in effect, a + some_separator + b + some_separator + c
.
To answer your question: in general, when concatenating many strings, it should be faster to use join
, and it will at least be more readable, especially when using a separator. For the case given in the question, I would instead use an f-string:
def greeting(name: str) -> str:
return f'Hello {name}'