String concatenation without '+' operator
To answer your second question: There is no difference at all (at least with the implementation I use). Disassembling both statements, they are rendered as LOAD_CONST STORE_FAST
. They are equivalent.
From the docs:
Multiple adjacent string literals (delimited by whitespace), possibly using different quoting conventions, are allowed, and their meaning is the same as their concatenation. Thus, "hello" 'world' is equivalent to "helloworld".
Statement 3 doesn't work because:
The ‘+’ operator must be used to concatenate string expressions at run time.
Notice that the title of the subheader in the docs is "string literal concatenation" too. This only works for string literals, not other objects.
There's probably no difference. If there is, it's probably extremely tiny and nothing that anyone should worry about.
Also, understand that there can be dangers to this:
>>> def foo(bar, baz=None):
... return bar
...
>>> foo("bob"
... "bill")
'bobbill'
This is a perfect example of where Errors should never pass silently. What if I wanted "bill"
to be the argument baz
? I have forgotton a comma, but no error is raised. Instead, concatenation has taken place.
This is implicit string literal concatenation. It only happens with string literals, not variables or other expressions that evaluate to strings. There used to be a (tiny) performance difference, but these days, the peephole optimizer should render the forms essentially equivalent.
You can use %s
as this is more efficient than using + sign.
>>> string2 = "%s %s" %('Hello', 'World')
>>> string2
'Hello World'
(OR)
one more method is .format
>>> string2 = "{0} {1}".format("Hello", "World")
>>> string2
'Hello World'
>>>