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