You don’t have to add them into a list to use .join
, it just has to be an iterable of some form, "".join(("a", "b", "c",))
. Bear in mind that most containers woudln’t copy the data itself, just references to the data. When you say copy-paste do you mean the variable names or the string contents? Because a string literal would arguably be better still but I don’t think that’s what you’re looking for.
The problem with the loop style concatenation +=
or +
is that strings are immutable in Python, so each time you add a new string you get a new string object which can add up to an awful lot of overhead very quickly in Big O terms (for three short strings that might not matter much at all though).
I’d hazard a guess that .join
that janbazant mentioned before would be the best option under the greatest number of circumstances (it’s a single line, readable and implemented in C). You’d really need to start profiling them if you had to push for more efficiency than that.
Edit:
Just cottoned on to the fact you’re asking about writing it efficiently rather than execution wise (I think).
For the most part you probably won’t ever have hundreds of uniquely named strings (unless someone made some terrible design decisions) and it’s much more likely they’d be in a container (a list or similar) already. If you do find yourself in that position consider refactoring the code that led to that situation.
If you had to write it out then your options are like those below (by no means an exhaustive list if you’re feeling creative!). Personally I’d be a fan of option #1 in this case because it’s pretty obvious what’s going on.
#1
message = string1 + string2 + string3 + string4 + string5 + string6
#2
message = "".join((string1, string2, string3, string4, string5, string6,))
#3
message = f"{string1}{string2}{string3}{string4}{string5}{string}"
#4
message = ""
for partial_msg in (string1, string2, string3, string4, string5, string6,):
message += partial_msg
If you actually meant execution efficiency then you’d probably want to profile these (but I don’t think #4 is particularly efficient or readable).