简体   繁体   中英

Is it ever appropriate to join two strings using the plus sign (+) over concatenating with curly brackets ({}) and `format` in Python 2.7?

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?

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 know you are dealing with simple strings, then, yes, Simple is better than complex . Formatting capability is great, and something like

“lit1” + var + “lit2” 

is a definite code smell.

Your example isn't and the extra complexity of the template based version is a slight extra cognitive load which I would avoid, or at least not strive for, despite using templating extensively.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM