I'm trying to write clean and concise code, and in a lot of code I look over sometimes I see people are inconsistent in their code. What I'm asking is, is there ever an instance where this
print("Cars on the road: " + cars)
is more appropriate than this
print("Cars on the road: {}".format(cars))
or is it just a matter of preference?
+ is the symbol for addition. Concatenation is not addition. Addition is commutative ( a + b == b + a ), concatenation isn't ( "Hello" + "World" != "World" + "Hello" ).
The + operator lets you combine two or more strings in Python. This operator is referred to as the Python string concatenation operator. The + operator should appear between the two strings you want to merge. This code concatenates, or merges, the Python strings “Hello ” and “World”.
If you concatenate Stings in loops for each iteration a new intermediate object is created in the String constant pool. This is not recommended as it causes memory issues.
One of the most popular methods to concatenate two strings in Python (or more) is using the + operator. The + operator, when used with two strings, concatenates the strings together to form one.
Concatenation is the process of appending one string to the end of another string. You concatenate strings by using the + operator. For string literals and string constants, concatenation occurs at compile time; no run-time concatenation occurs.
Concatenate multiple strings The most common among them is using the plus (“+”) operator. You can combine both string variables and string literals using the “+” operator. However, there's another method that allows an easy way of concatenating multiple strings. It is using the in-place (+=) operator.
The big functional difference between the two examples you gave is that when you concatenate with +
, the operation will fail if the object on the right side of the operand is not a string:
"abc" + object()
For instance will cause the following:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: Can't convert 'object' object to str implicitly
This is true even if the object on the right side implements the __str__
method:
class Foo:
def __str__(self):
return "str"
Using format however will automatically convert a passed argument using the __str__
method:
"{}".format(Foo()) # "str"
There are some situations where this behavior might not be desirable or necessary, such as when you are simply concatenating a string literal with an object that is expected to be a string.
In all other cases I agree with the post cited in the comments which provide plenty of good reasons why formatting is more idiomatically correct and potentially more efficient.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With