Python string formatting: % vs concatenation

前端 未结 4 988
不思量自难忘°
不思量自难忘° 2020-12-09 12:05

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

4条回答
  •  再見小時候
    2020-12-09 13:00

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

提交回复
热议问题