Python字符串格式:%与.format

Python 2.6引入了str.format()方法,其语法与现有的%运算符略有不同。 哪个更好,哪些情况?

  • 以下使用每种方法,并有相同的结果,所以有什么区别?

    #!/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中出现字符串格式? 例如,如果我的日志记录级别设置为“高”,我仍然会执行下面的%操作。 如果是这样,有没有办法避免这种情况?

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

  • 要回答你的第一个问题...... .format在许多方面似乎更复杂。 关于%的恼人的事情也是它如何可以采取变量或元组。 你会认为以下将始终有效:

    "hi there %s" % name
    

    但是,如果name碰巧是(1, 2, 3) ,它将抛出一个TypeError 。 为了保证它始终打印,你需要这样做

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

    这只是丑陋的。 .format没有这些问题。 同样在你给出的第二个例子中, .format例子看起来更清晰。

    你为什么不使用它?

  • 不知道这件事(我在读这本书之前)
  • 必须与Python 2.5兼容

  • 要回答第二个问题,字符串格式化与其他任何操作同时发生 - 当字符串格式化表达式被评估时。 而且Python不是一种懒惰的语言,因此在调用函数之前对表达式进行评估,因此在你的log.debug例子中,表达式"some debug info: %s"%some_info将首先评估,例如"some debug info: roflcopters are active" ,那么该字符串将被传递给log.debug()


    模运算符(%)不能做的事,afaik:

    tu = (12,45,22222,103,6)
    print '{0} {2} {1} {2} {3} {2} {4} {2}'.format(*tu)
    

    结果

    12 22222 45 22222 103 22222 6 22222
    

    很有用。

    另一点:作为函数的format()可以用作其他函数的参数:

    li = [12,45,78,784,2,69,1254,4785,984]
    print map('the number is {}'.format,li)   
    
    print
    
    from datetime import datetime,timedelta
    
    once_upon_a_time = datetime(2010, 7, 1, 12, 0, 0)
    delta = timedelta(days=13, hours=8,  minutes=20)
    
    gen =(once_upon_a_time +x*delta for x in xrange(20))
    
    print 'n'.join(map('{:%Y-%m-%d %H:%M:%S}'.format, gen))
    

    结果是:

    ['the number is 12', 'the number is 45', 'the number is 78', 'the number is 784', 'the number is 2', 'the number is 69', 'the number is 1254', 'the number is 4785', 'the number is 984']
    
    2010-07-01 12:00:00
    2010-07-14 20:20:00
    2010-07-28 04:40:00
    2010-08-10 13:00:00
    2010-08-23 21:20:00
    2010-09-06 05:40:00
    2010-09-19 14:00:00
    2010-10-02 22:20:00
    2010-10-16 06:40:00
    2010-10-29 15:00:00
    2010-11-11 23:20:00
    2010-11-25 07:40:00
    2010-12-08 16:00:00
    2010-12-22 00:20:00
    2011-01-04 08:40:00
    2011-01-17 17:00:00
    2011-01-31 01:20:00
    2011-02-13 09:40:00
    2011-02-26 18:00:00
    2011-03-12 02:20:00
    

    假设你使用Python的logging模块,你可以将字符串格式参数作为参数传递给.debug()方法,而不是自己做格式化:

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

    这避免了格式化,除非记录器实际记录了某些内容。

    链接地址: http://www.djcxy.com/p/28299.html

    上一篇: Python string formatting: % vs. .format

    下一篇: Center NSTextAttachment image next to single line UILabel