简体   繁体   English

在Python 2.7中使用加号(+)连接大括号({})和`format`是否合适?

[英]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: 即使右侧的对象实现__str__方法,也是__str__

class Foo:
    def __str__(self):
        return "str"

Using format however will automatically convert a passed argument using the __str__ method: 但是,使用格式将使用__str__方法自动转换传递的参数:

"{}".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. 你的例子不是,基于模板的版本的额外复杂性是一个轻微的额外认知负荷, 会避免,或至少不努力,尽管广泛使用模板。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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