Python 字符串格式:% vs 连接 [英] Python string formatting: % vs concatenation

查看:40
本文介绍了Python 字符串格式:% vs 连接的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我正在开发一个应用程序,我在其中执行一些请求以获取对象 ID.在每一个之后,我调用一个方法 (get_actor_info()) 将此 id 作为参数传递(见下面的代码).

I'm developing an application in which I perform some requests to get an object id. After each one of them, I call a method (get_actor_info()) passing this id as an argument (see code below).

ACTOR_CACHE_KEY_PREFIX = 'actor_'

def get_actor_info(actor_id):
    cache_key = ACTOR_CACHE_KEY_PREFIX + str(actor_id)

可以注意到,我将 actor_id 转换为 string 并用前缀连接它.但是,我知道我可以通过多种其他方式来做到这一点(例如,.format()'%s%d'),这导致了我的问题:'%s%d' 在可读性、代码约定和效率方面比字符串连接更好吗?

As can be noticed, I'm casting actor_id to string and concatenating it with a prefix. However, I know I could do it in multiple other ways (.format() or '%s%d', for instance) and that results in my question: would '%s%d' be better than string concatenation in terms of readability, code convention and efficiency?

谢谢

推荐答案

这很容易变成一个基于意见的线程,但我发现格式在大多数情况下更具可读性,更易于维护.更容易想象最终字符串的样子,而无需进行心理连接".例如,以下哪个更易读?

This could easily become an opinion-based thread, but I find formatting to be more readable in most cases, and more maintainable. It's easier to visualize what the final string will look like, without doing "mental concatenation". Which of these is more readable, for example?

errorString = "Exception occurred ({}) while executing '{}': {}".format(
    e.__class__.__name__, task.name, str(e)
)

或者:

errorString = "Exception occurred (" + e.__class__.__name__
    + ") while executing '" + task.name + "': " + str(e)

至于使用%还是.format(),我可以更客观的回答:使用.format().% 是旧样式",并且根据 Python 文档它们可能很快会被删除:

As for whether to use % or .format(), I can answer more objectively: Use .format(). % is the "old-style", and, per the Python Documentation they may soon be removed:

由于 str.format() 比较新,很多 Python 代码仍然使用 % 操作符.但是,由于这种旧的格式样式最终会从语言中删除,因此通常应该使用 str.format().

Since str.format() is quite new, a lot of Python code still uses the % operator. However, because this old style of formatting will eventually be removed from the language, str.format() should generally be used.

文档的后续版本不再提及这一点,但尽管如此,.format() 是未来的方向;使用它!

Later versions of the documentation have stopped mentioning this, but nonetheless, .format() is the way of the future; use it!

连接速度更快,但这不应该是一个问题.将您的代码可读性和可维护性作为第一线目标,然后优化您以后需要优化的部分.过早的优化是万恶之源;)

Concatenation is faster, but that should not be a concern. Make your code readable and maintainable as a first-line goal, and then optimize the parts you need to optimize later. Premature optimization is the root of all evil ;)

这篇关于Python 字符串格式:% vs 连接的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆