Is there any difference between
str_ = "foo" + "bar"
and
str_ = "{:s}{:s}".format("foo","bar")
or is it simply preference?
Is there any difference between
str_ = "foo" + "bar"
and
str_ = "{:s}{:s}".format("foo","bar")
or is it simply preference?
Semantically? No, both end up joining "foo"
and "bar"
and assigning them to str
.
Computationally? Surely, Python will create the literal for "foobar"
during compilation, the str = "foo" + "bar"
assignment will be faster.
From a readability aspect? Again, str = "foo" + "bar"
is surely more clear and concise.
The common errata in both your examples is that you're assigning to str
which is a built-in name, so don't, you mask it.
If you want to see the actual difference:
import dis
def concat():
return 'foo' + 'bar'
def format():
return '{}{}'.format('foo', 'bar')
dis.dis(concat)
print('*'*80)
dis.dis(format)
To complete @Jim explanation, here's a little benchmark showing a comparison between both methods:
# measure execution time
import timeit
def f1(num_iterations):
for i in range(num_iterations):
value = "foo" + "bar"
def f2(num_iterations):
for i in range(num_iterations):
value = "{:s}{:s}".format("foo", "bar")
N = 100000000
print timeit.timeit('f1(N)', setup='from __main__ import f1, N', number=1)
print timeit.timeit('f2(N)', setup='from __main__ import f2, N', number=1)
The results in my laptop gives: f1=4.49492255239s and f2=47.5562411453s
So the conclusion is using format when N is big will be much slower than using the simpler str concatenation version.
Regards Jim answer, using +
operator with many strings, can be slow.
Avoid doing something like this:
s = ' '
for p in parts:
s += p
each +=
operation create a new string. To avoid that, use join()
.
' '.join(parts)
In your example, you don't need to use +
. Simply place them adjacent to each other with no +.
string = 'foo' 'bar'
print(string)
>"foobar"