首页 文章

Python字符串格式:%vs. .format

提问于
浏览
1209

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中发生字符串格式化?例如,如果我的日志记录级别设置为HIGH,我仍然会执行以下 % 操作?如果是这样,有没有办法避免这种情况?
log.debug("some debug info: %s" % some_info)

15 回答

  • 54

    正如我今天发现的那样,通过 % 格式化字符串的旧方法不支持 Decimal ,Python的十进制定点和浮点运算模块,开箱即用 .

    示例(使用Python 3.3.5):

    #!/usr/bin/env python3
    
    from decimal import *
    
    getcontext().prec = 50
    d = Decimal('3.12375239e-24') # no magic number, I rather produced it by banging my head on my keyboard
    
    print('%.50f' % d)
    print('{0:.50f}'.format(d))
    

    输出:

    0.00000000000000000000000312375239000000009907464850 0.00000000000000000000000312375239000000000000000000

    肯定可能有解决办法,但你仍然可以考虑立即使用 format() 方法 .

  • 284

    回答你的第一个问题... .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() .

  • 126

    如果你的python> = 3.6,F字符串格式的文字是你的新朋友 .

    它更简单,更干净,性能更好 .

    In [1]: params=['Hello', 'adam', 42]
    
    In [2]: %timeit "%s %s, the answer to everything is %d."%(params[0],params[1],params[2])
    448 ns ± 1.48 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    In [3]: %timeit "{} {}, the answer to everything is {}.".format(*params)
    449 ns ± 1.42 ns per loop (mean ± std. dev. of 7 runs, 1000000 loops each)
    
    In [4]: %timeit f"{params[0]} {params[1]}, the answer to everything is {params[2]}."
    12.7 ns ± 0.0129 ns per loop (mean ± std. dev. of 7 runs, 100000000 loops each)
    
  • 52

    % 比我的测试中的 format 性能更好 .

    测试代码:

    Python 2.7.2:

    import timeit
    print 'format:', timeit.timeit("'{}{}{}'.format(1, 1.23, 'hello')")
    print '%:', timeit.timeit("'%s%s%s' % (1, 1.23, 'hello')")
    

    结果:

    > format: 0.470329046249
    > %: 0.357107877731
    

    Python 3.5.2

    import timeit
    print('format:', timeit.timeit("'{}{}{}'.format(1, 1.23, 'hello')"))
    print('%:', timeit.timeit("'%s%s%s' % (1, 1.23, 'hello')"))
    

    结果

    > format: 0.5864730989560485
    > %: 0.013593495357781649
    

    它看起来在Python2中,差异很小,而在Python3中, %format 快得多 .

    感谢@Chris Cogdon提供的示例代码 .

  • 28

    但有一件事是,如果你有嵌套的大括号,将不适用于格式,但 % 将起作用 .

    例:

    >>> '{{0}, {1}}'.format(1,2)
    Traceback (most recent call last):
      File "<pyshell#3>", line 1, in <module>
        '{{0}, {1}}'.format(1,2)
    ValueError: Single '}' encountered in format string
    >>> '{%s, %s}'%(1,2)
    '{1, 2}'
    >>>
    
  • 24

    假设你是're using Python' s logging 模块,你可以将字符串格式化参数作为参数传递给 .debug() 方法,而不是自己进行格式化:

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

    这避免了格式化,除非 Logger 实际记录的东西 .

  • 95

    作为旁注,您不必为了使用新的样式格式与日志记录而受到性能影响 . 您可以将任何对象传递给实现 __str__ 魔术方法的 logging.debuglogging.info 等 . 当日志记录模块确定它必须发出消息对象(无论它是什么)时,它会在执行此操作之前调用 str(message_object) . 所以你可以这样做:

    import logging
    
    
    class NewStyleLogMessage(object):
        def __init__(self, message, *args, **kwargs):
            self.message = message
            self.args = args
            self.kwargs = kwargs
    
        def __str__(self):
            args = (i() if callable(i) else i for i in self.args)
            kwargs = dict((k, v() if callable(v) else v) for k, v in self.kwargs.items())
    
            return self.message.format(*args, **kwargs)
    
    N = NewStyleLogMessage
    
    # Neither one of these messages are formatted (or calculated) until they're
    # needed
    
    # Emits "Lazily formatted log entry: 123 foo" in log
    logging.debug(N('Lazily formatted log entry: {0} {keyword}', 123, keyword='foo'))
    
    
    def expensive_func():
        # Do something that takes a long time...
        return 'foo'
    
    # Emits "Expensive log entry: foo" in log
    logging.debug(N('Expensive log entry: {keyword}', keyword=expensive_func))
    

    这些都在Python 3文档(https://docs.python.org/3/howto/logging-cookbook.html#formatting-styles)中描述 . 但是,它也适用于Python 2.6(https://docs.python.org/2.6/library/logging.html#using-arbitrary-objects-as-messages) .

    使用这种技术的一个优点,除了它的格式化风格不可知的事实,是它允许惰性值,例如上面的函数 expensive_func . 这为Python文档中提供的建议提供了更优雅的替代方案:https://docs.python.org/2.6/library/logging.html#optimization .

  • 2

    .format 的另一个优点(我在答案中没有看到):它可以采用对象属性 .

    In [12]: class A(object):
       ....:     def __init__(self, x, y):
       ....:         self.x = x
       ....:         self.y = y
       ....:         
    
    In [13]: a = A(2,3)
    
    In [14]: 'x is {0.x}, y is {0.y}'.format(a)
    Out[14]: 'x is 2, y is 3'
    

    或者,作为关键字参数:

    In [15]: 'x is {a.x}, y is {a.y}'.format(a=a)
    Out[15]: 'x is 2, y is 3'
    

    据我所知, % 无法做到这一点 .

  • 33

    对于python版本> = 3.6(参见PEP 498

    s1='albha'
    s2='beta'
    
    f'{s1}{s2:>10}'
    
    #output
    'albha      beta'
    
  • 866

    从Python 3.6(2016)开始,您可以使用f-strings替换变量:

    >>> origin = "London"
    >>> destination = "Paris"
    >>> f"from {origin} to {destination}"
    'from London to Paris'
    

    注意 f" 前缀 . 如果您在Python 3.5或更早版本中尝试此操作,您将获得 SyntaxError .

    https://docs.python.org/3.6/reference/lexical_analysis.html#f-strings

  • 3

    模数运算符(%)不能做的事情,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
    
  • 14

    % 可能有用的一种情况是在格式化正则表达式时 . 例如,

    '{type_names} [a-z]{2}'.format(type_names='triangle|square')
    

    提出 IndexError . 在这种情况下,您可以使用:

    '%(type_names)s [a-z]{2}' % {'type_names': 'triangle|square'}
    

    这可以避免将正则表达式写为 '{type_names} [a-z]{{2}}' . 当你有两个正则表达式时,这可能很有用,其中一个正则单独使用而没有格式,但两者的串联都是格式化的 .

  • 5

    但是请小心,刚才我在现有代码中尝试用 .format 替换所有 % 时发现了一个问题: '{}'.format(unicode_string) will try to encode unicode_string and will probably fail.

    看看这个Python交互式会话日志:

    Python 2.7.2 (default, Aug 27 2012, 19:52:55) 
    [GCC 4.1.2 20080704 (Red Hat 4.1.2-48)] on linux2
    ; s='й'
    ; u=u'й'
    ; s
    '\xd0\xb9'
    ; u
    u'\u0439'
    

    s 只是一个字符串(在Python3中称为'byte array'), u 是一个Unicode字符串(在Python3中称为'string'):

    ; '%s' % s
    '\xd0\xb9'
    ; '%s' % u
    u'\u0439'
    

    当您将一个Unicode对象作为参数提供给 % 运算符时,即使原始字符串不是Unicode,它也会生成一个Unicode字符串:

    ; '{}'.format(s)
    '\xd0\xb9'
    ; '{}'.format(u)
    Traceback (most recent call last):
      File "<stdin>", line 1, in <module>
    UnicodeEncodeError: 'latin-1' codec can't encode character u'\u0439' in position 0: ordinal not in range(256)
    

    但是 .format 函数会引发"UnicodeEncodeError":

    ; u'{}'.format(s)
    u'\xd0\xb9'
    ; u'{}'.format(u)
    u'\u0439'
    

    只有当原始字符串是Unicode时,它才能使用Unicode参数 .

    ; '{}'.format(u'i')
    'i'
    

    或者如果参数字符串可以转换为字符串(所谓的'字节数组')

  • 0

    PEP 3101建议用Python 3中新的高级字符串格式替换 % 运算符,它将是默认值 .

  • 8

    我想补充一点,自3.6版以来,我们可以使用如下的fstrings

    foo = "john"
    bar = "smith"
    print(f"My name is {foo} {bar}")
    

    哪个给

    我的名字是约翰史密斯

    Everything is converted to strings

    mylist = ["foo", "bar"]
    print(f"mylist = {mylist}")
    

    结果:

    mylist = ['foo','bar']

    you can pass function, like in others formats method

    print(f'Hello, here is the date : {time.strftime("%d/%m/%Y")}')
    

    举个例子

    您好,这是日期:16/04/2018

相关问题