-1

Is there any difference between

str_ = "foo" + "bar"

and

str_ = "{:s}{:s}".format("foo","bar")

or is it simply preference?

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
socrates
  • 327
  • 2
  • 11

4 Answers4

2

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.

Dimitris Fasarakis Hilliard
  • 150,925
  • 31
  • 268
  • 253
2

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)
Wayne Werner
  • 49,299
  • 29
  • 200
  • 290
1

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.

BPL
  • 9,632
  • 9
  • 59
  • 117
  • This is a strange use of `timeit`. You've put the loop in the measurement and only run it once. For `f1` the cost of the loop is much larger than the cost of the line you are trying to time that its result is meaningless. `timeit('value = "foo" + "bar"')` would be the more standard way of doing it. – tdelaney Aug 16 '16 at 22:43
0

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"
levi
  • 22,001
  • 7
  • 73
  • 74