I understand that we should use %s
to concatenate a string rather than +
in Python.
I could do any of:
hello = "hello"
world = "world"
print hello + " " + world
print "%s %s" % (hello, world)
print "{} {}".format(hello, world)
print ' '.join([hello, world])
But why should I use anything other than the +
? It's quicker to write concatenation with a simple +
. Then if you look at the formatting string, you specify the types e.g. %s
and %d
and such. I understand it could be better to be explicit about the type.
But then I read that using +
for concatenation should be avoided even though it's easier to type. Is there a clear reason that strings should be concatenated in one of those other ways?
%s
isn't for concatenation, it's a conversion specification for string formatting derived from C'sprintf(3)
. There are cases to for using that or a concatenation operator; which you use should be based on judgment of the situation, not dogma. How easy it is to write the code is entirely irrelevant because you're only going to do that once.print(f"{hello} {world}")
, has readability of concatenation since variables are seen where they occur in the string, and is faster thanstr.format
.shell
,perl
and other languages:echo "$hello $world"
.