字符串格式:%与.format [英] String formatting: % vs. .format

查看:122
本文介绍了字符串格式:%与.format的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

Python 2.6引入了 str.format() 方法,与现有%运算符的语法略有不同.哪种更好,什么情况下适合?

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

  1. 以下内容使用每种方法并具有相同的结果,所以有什么区别?

  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!"

  • 此外,何时在Python中进行字符串格式化?例如,如果我的日志记录级别设置为HIGH,那么执行以下%操作是否还会受到影响?如果是这样,有办法避免这种情况吗?

  • Furthermore when does string formatting occur in 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)
    

  • 推荐答案

    要回答第一个问题... .format似乎在许多方面都更加复杂.关于%的一个烦人的事情是它如何可以接受变量或元组.您会认为以下内容将始终有效:

    To answer your first question... .format just seems more sophisticated in many ways. An annoying thing about % is also how it can either take a variable or a tuple. You'd think the following would always work:

    "hi there %s" % name
    

    但是,如果name恰好是(1, 2, 3),它将抛出TypeError.为了确保它始终打印,您需要这样做

    yet, if name happens to be (1, 2, 3), it will throw a TypeError. To guarantee that it always prints, you'd need to do

    "hi there %s" % (name,)   # supply the single argument as a single-item tuple
    

    这很丑. .format没有这些问题.同样在您给出的第二个示例中,.format示例看起来更加简洁.

    which is just ugly. .format doesn't have those issues. Also in the second example you gave, the .format example is much cleaner looking.

    您为什么不使用它?

    • 不知道(我在阅读本文之前)
    • 必须与Python 2.5兼容

    要回答您的第二个问题,字符串格式化与任何其他操作同时发生-在计算字符串格式化表达式时.而且,Python不是一种惰性语言,它会在调用函数之前先评估表达式,因此在您的log.debug示例中,表达式"some debug info: %s"%some_info首先会评估为,例如"some debug info: roflcopters are active",则该字符串将传递给log.debug().

    To answer your second question, string formatting happens at the same time as any other operation - when the string formatting expression is evaluated. And Python, not being a lazy language, evaluates expressions before calling functions, so in your log.debug example, the expression "some debug info: %s"%some_infowill first evaluate to, e.g. "some debug info: roflcopters are active", then that string will be passed to log.debug().

    这篇关于字符串格式:%与.format的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

    查看全文
    登录 关闭
    扫码关注1秒登录
    发送“验证码”获取 | 15天全站免登陆