String formatting: % vs. .format vs. string literal

后端 未结 16 2721
青春惊慌失措
青春惊慌失措 2020-11-21 04:18

Python 2.6 introduced the str.format() method with a slightly different syntax from the existing % operator. Which is better and for what situations?

Pyt

16条回答
  •  轻奢々
    轻奢々 (楼主)
    2020-11-21 04:52

    Assuming you're using Python's logging module, you can pass the string formatting arguments as arguments to the .debug() method rather than doing the formatting yourself:

    log.debug("some debug info: %s", some_info)
    

    which avoids doing the formatting unless the logger actually logs something.

提交回复
热议问题