Python String Formatting – % vs Concatenation Explained

pythonstringstring-formatting

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)

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?

Thanks

Best Answer

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)
)

Or:

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

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:

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.

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 ;)