字符串格式:%vs..form

2024-04-20 08:38:35 发布

您现在位置:Python中文网/ 问答频道 /正文

Python 2.6引入了^{}方法,其语法与现有的%运算符略有不同。哪种情况更好?

  1. 下面使用的每种方法都有相同的结果,那么有什么区别呢?

    #!/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. 此外,Python中什么时候会出现字符串格式?例如,如果我的日志记录级别设置为HIGH,那么我是否仍会执行下面的%操作?如果是的话,有没有办法避免呢?

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

Tags: 方法debuginfoanformatstringwith语法
3条回答

回答你的第一个问题。。。.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示例看起来更干净。

你为什么不使用它?

  • 不知道(我在读之前)
  • 必须与Python2.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)

这样可以避免格式化,除非记录器实际记录了一些内容。

相关问题 更多 >