字符串格式:%与.format

大憨熊 提交于 2020-04-06 02:58:40

问题:

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
易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!