字符串格式:%与.format - String formatting: % vs. .format

08/11 03:38
阅读数 36

问题:

Python 2.6 introduced the str.format() method with a slightly different syntax from the existing % operator. Python 2.6引入了str.format()方法,其语法与现有的%运算符略有不同。 Which is better and for what situations? 哪个更好,什么情况下适合?

  1. The following uses each method and has the same outcome, so what is the difference? 以下使用每种方法并具有相同的结果,那么有什么区别?

    #!/usr/bin/python sub1 = "python string!" sub2 = "an arg" a = "i am a %s" % sub1 b = "i am a {0}".format(sub1) c = "with %(kwarg)s!" % {'kwarg':sub2} d = "with {kwarg}!".format(kwarg=sub2) print a # "i am a python string!" print b # "i am a python string!" print c # "with an arg!" print d # "with an arg!"
  2. Furthermore when does string formatting occur in Python? 此外,何时在Python中进行字符串格式化? For example, if my logging level is set to HIGH will I still take a hit for performing the following % operation? 例如,如果我的日志记录级别设置为“高”,执行以下%操作是否还会受到影响? And if so, is there a way to avoid this? 如果是这样,有办法避免这种情况吗?

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

解决方案:

参考一: https://stackoom.com/question/LKB2/字符串格式-与-format
参考二: https://oldbug.net/q/LKB2/String-formatting-vs-format
展开阅读全文
打赏
0
0 收藏
分享
加载中
更多评论
打赏
0 评论
0 收藏
0
分享
在线直播报名
返回顶部
顶部