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

Nor*_*sUp 1323 python performance logging string-formatting

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

  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!"
    
    Run Code Online (Sandbox Code Playgroud)
  2. 此外,何时在Python中发生字符串格式化?例如,如果我的日志记录级别设置为HIGH,我仍然会执行以下%操作吗?如果是这样,有没有办法避免这种情况?

    log.debug("some debug info: %s" % some_info)
    
    Run Code Online (Sandbox Code Playgroud)

Cla*_*diu 940

回答你的第一个问题...... .format在许多方面似乎更复杂.令人讨厌的%是它如何能够采用变量或元组.您认为以下内容始终有效:

"hi there %s" % name
Run Code Online (Sandbox Code Playgroud)

然而,如果name恰好是(1, 2, 3),它会抛出一个TypeError.为了保证它始终打印,您需要这样做

"hi there %s" % (name,)   # supply the single argument as a single-item tuple
Run Code Online (Sandbox Code Playgroud)

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

你为什么不用它?

  • 不知道它(我在读这篇文章之前)
  • 必须与Python 2.5兼容

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

  • 请注意,您将浪费时间用于`log.debug("something:%s"%x)`但不能用于`log.debug("something:%s",x)`字符串格式化将在方法中处理如果不记录,你将无法获得性能.一如既往,Python预测您的需求=) (123认同)
  • 怎么样"%(a)s,%(a)s"%{'a':'test'}` (111认同)
  • 特德:这是一个看起来更糟糕的黑客,与"{0},{0}".格式('test')`相同. (62认同)
  • @cfi:如果你的意思是'printf("%2 $ d",1,3)`打印出"3",那是在POSIX中指定的,而不是C99.您引用了注释的手册页,"C99标准不包含使用'$'的样式......". (27认同)
  • 重点是:新语法允许重新排序项目的一个反复出现的论点是一个没有实际意义的点:您可以使用旧语法执行相同操作.大多数人都不知道这实际上已经在Ansi C99标准中定义了!查看最近的`man sprintf`副本,了解`%`占位符中的`$`表示法 (19认同)
  • .format可能更优雅,但它可能比%慢5倍,根据你的目标可能很重要. (4认同)
  • 实际上,与使用索引标记的新式格式相比,旧式格式化要慢得多.这可能取决于你如何使用它.另外,`str.format`更像面向对象,因为它只是`str`实例上的一个方法而不是特殊语法.这更符合python的"显性优于隐式"理念,因为它避开了额外的语法. (4认同)
  • 汤姆:如果你的意图只是两次使用同一个物体,而不是增加清晰度,那确实是一个黑客攻击.如果你以某种方式坚持使用`%`(例如因为它在你的API中被烘焙),那么你当然必须使用它. (3认同)
  • 另外,"%d atoms"%10*3`给出"10个原子10个原子10个原子",但"10个原子10个原子10个原子"给出"9个原子" (2认同)
  • 我可以认为.format的唯一缺点是键入`“ {0}”。format(var)`所花的时间比`“%s”%var`所花的时间更长。 (2认同)

eyq*_*uem 303

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

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

结果

12 22222 45 22222 103 22222 6 22222
Run Code Online (Sandbox Code Playgroud)

很有用.

另一点: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))
Run Code Online (Sandbox Code Playgroud)

结果是:

['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
Run Code Online (Sandbox Code Playgroud)

  • 你可以像`map`一样使用旧式格式化,就像格式一样容易.`map('some_format_string_%s'.__ mod __,some_iterable)` (17认同)
  • 'modulo'是指在除法后评估余数的运算符.在这种情况下,百分号不是模运算符. (17认同)
  • @MarcH:`printf("%2 $ s%1 $ s \n","One","Two");`用`gcc -std = c99 test.c -o test`编译,输出为`2 One`.但是我更正了:[它实际上是一个POSIX扩展](http://stackoverflow.com/a/6322594/923794)而不是C.我在C/C++标准中再也找不到它,我认为我在那里看过.该代码甚至可以使用'c90'std标志.[`sprintf`手册页](http://linux.die.net/man/3/sprintf).[This](http://www.cplusplus.com/reference/cstdio/printf/#compatibility)没有列出它,但允许libs实现超集.我的原始参数仍然有效,用`Posix'替换`C` (9认同)
  • 我在这里的第一条评论不适用于这个答案.我为这句话感到后悔.在Python中,我们不能使用模运算符`%`来重新排序占位符.为了评论的一致性,我仍然不想删除第一条评论.我为在这里发泄我的愤怒而道歉.它针对的是经常声明的旧语法本身不允许这样做.我们可以引入std Posix扩展,而不是创建一个全新的语法.我们两个都可以. (8认同)
  • @cfi:请在C99中重写上面的例子来证明你是对的 (3认同)
  • @Octopus:来自https://docs.python.org/release/2.5/lib/typesseq-strings.html“字符串和Unicode对象有一个独特的内置操作:%运算符(模)。” 所以,是的,它*是*模运算符,并且它具有神奇的方法“__mod__”,即使它在这种用法中不具有模的数学语义。 (3认同)

Woo*_*ble 142

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

log.debug("some debug info: %s", some_info)
Run Code Online (Sandbox Code Playgroud)

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

  • 这样做的主要好处不在于性能(与日志记录输出相比,字符串插值会很快,例如在终端中显示,保存到磁盘)如果你有一个日志记录聚合器,那就是可以告诉你"你有12个这个错误信息的实例",即使它们都有不同的'some_info'值.如果在将字符串传递给log.debug之前完成字符串格式化,那么这是不可能的.聚合器只能说"你有12条不同的日志消息" (26认同)
  • @Cito:见:http://plumberjack.blogspot.co.uk/2010/10/supporting-alternative-formatting.html (15认同)
  • 您可以使用这样的dict格式:`log.debug("一些调试信息:%(this)s和%(那)s",dict(这='Tom',那='Jerry'))`但是,你不能在这里使用新的`.format()`语法,甚至在Python 3.3中也是如此,这是一种耻辱. (12认同)
  • 这是我刚刚学到的一些有用的信息.很遗憾它没有自己的问题,因为它似乎与主要问题分开.可惜OP没有在两个单独的问题中分开他的问题. (10认同)
  • 如果您关注性能,请使用文字dict {}语法而不是dict()类实例化:http://doughellmann.com/2012/11/the-performance-impact-of-using-dict-instead-of -in-CPython的,2-7-2.html (6认同)
  • @VinaySajip:很酷,感谢您的信息并抱歉传播错误信息.它也出现在这里的"3.2中的新内容"文章中:http://docs.python.org/3.2/whatsnew/3.2.html#logging.很有用. (2认同)
  • @JonathanHartley:取决于您的聚合器的复杂程度。 (2认同)

Col*_*nic 116

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

>>> origin = "London"
>>> destination = "Paris"
>>> f"from {origin} to {destination}"
'from London to Paris'
Run Code Online (Sandbox Code Playgroud)

注意f"前缀.如果你在Python 3.5或更早版本中尝试这个,你会得到一个SyntaxError.

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

  • 这不能回答问题。提到 f-strings 的另一个答案至少谈到了性能:/sf/answers/3581748341/ (5认同)

Bra*_*orm 58

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

  • 不真实:"通过保留现有机制,可以维持向后兼容性."; 当然,`.format`不会_replace_`%`字符串格式化. (13认同)
  • 不,BrainStorms假设是真的:"打算替代现有的'%'".Tobias引用意味着两个系统将共存一段时间.RTFPEP (9认同)

rsl*_*lnx 53

但是请小心,刚才我在尝试%.format现有代码替换所有代码时发现了一个问题:'{}'.format(unicode_string)将尝试编码unicode_string并且可能会失败.

只需看看这个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'
Run Code Online (Sandbox Code Playgroud)

s只是一个字符串(在Python3中称为"字节数组")并且u是一个Unicode字符串(在Python3中称为"字符串"):

; '%s' % s
'\xd0\xb9'
; '%s' % u
u'\u0439'
Run Code Online (Sandbox Code Playgroud)

当您将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)
Run Code Online (Sandbox Code Playgroud)

但该.format函数将引发"UnicodeEncodeError":

; u'{}'.format(s)
u'\xd0\xb9'
; u'{}'.format(u)
u'\u0439'
Run Code Online (Sandbox Code Playgroud)

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

; '{}'.format(u'i')
'i'
Run Code Online (Sandbox Code Playgroud)

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

  • 除非真正需要新的`format`方法的附加功能,否则没有理由改变工作代码...... (12认同)
  • 我认为.format()函数对字符串比%更安全.通常我会看到初学者的错误,例如"p1 =%s p2 =%d"%"abc",2`或""p1 =%s p2 =%s"%(tuple_p1_p2,)`.您可能认为这是编码器的错误,但我认为这只是一种奇怪的错误语法,对于快速脚本看起来不错,但对于生产代码却不好. (4认同)
  • 但是我不喜欢.format()的语法,我会对旧的`%s`,`%02d`更喜欢"p1 =%s p2 =%02d".format("abc", 2)`.我责怪那些发明并批准花括号格式的人,需要你像`{{}}`一样逃脱它们,看起来很难看. (3认同)
  • 例如?AFAIK,它已经不再需要; 我不认为`%`字符串插值可能会消失. (2认同)

mat*_*asg 35

.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'
Run Code Online (Sandbox Code Playgroud)

或者,作为关键字参数:

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

%据我所知,这是不可能的.

  • @dtheodor通过调整来使用关键字参数而不是位置参数...`'x是{ax},y是{ay}'.format(a = a)`.比两个示例更具可读性. (13认同)
  • 与等效的''是{0},y是{1}'.格式(ax,ay)`相比,这看起来比必要的更难以理解.只应在'ax`操作非常昂贵时使用. (4认同)
  • 这对于面向客户的应用程序非常有用,在这些应用程序中,您的应用程序使用用户提供的格式字符串提供一组标准格式选项.我经常用这个.例如,配置文件将具有一些"messagestring"属性,用户可以提供`您的订单,编号{订单[编号]}在{now:%Y-%m-%d%H:%处理M:%S},将在大约{orderη:%H:%M:%S}或其他任何他们想要的东西准备好.这比尝试使用旧格式化程序提供相同的功能要简单得多.它使用户提供的格式字符串更强大. (3认同)

bal*_*alu 31

正如我今天发现的那样,格式化字符串的旧方法%不支持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))
Run Code Online (Sandbox Code Playgroud)

输出:

0.00000000000000000000000312375239000000009907464850 0.00000000000000000000000312375239000000000000000000

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

  • 你是这么认为的,但是`str(d)`返回`"3.12375239e-24"`,而不是`"0.00000000000000000000000312375239000000000000000000"` (3认同)

lcl*_*ltj 29

%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')")
Run Code Online (Sandbox Code Playgroud)

结果:

> format: 0.470329046249
> %: 0.357107877731
Run Code Online (Sandbox Code Playgroud)

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')"))
Run Code Online (Sandbox Code Playgroud)

结果

> format: 0.5864730989560485
> %: 0.013593495357781649
Run Code Online (Sandbox Code Playgroud)

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

感谢@Chris Cogdon的示例代码.

  • 相反,`str.format`提供了更多功能(特别是类型专用格式,例如`'{0:%Y-%m-%d}'.format(datetime.datetime.utcnow())`).绩效不是所有工作的绝对要求.使用正确的工具完成工作. (41认同)
  • _"过早的优化是所有邪恶的根源"_左右Donald Knuth曾经说过...... (33认同)
  • 坚持使用众所周知的格式化方案(只要它适合需要,它在绝大多数情况下都适用),并且速度提高两倍,不是"过早优化",而是合理的.顺便说一句,'%`运算符允许重用`printf`知识; 字典插值是一个非常简单的原理扩展. (20认同)
  • 看起来像一个严重浪费的帖子,没有任何例子或推理,只是声称. (8认同)
  • 在一种情况下,我实际上经历了相反的情况.新式格式化更快.你能提供你用过的测试代码吗? (5认同)
  • 从我的测试来看,Python3和Python 2.7之间也存在巨大差异.`%`比Python 3中的`format()`更有效.我使用的代码可以在这里找到:https://github.com/rasbt/python_efficiency_tweaks/blob/master/test_code/string_subst_3.py和https://github.com/rasbt/python_efficiency_tweaks/blob/master/test_code/string_subst_2.py (2认同)

小智 17

如果你的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)
Run Code Online (Sandbox Code Playgroud)

  • 从 Python 3.11 开始,C 样式格式(使用 %s、%a 和 %r)[现在与相应的格式一样快](https://docs.python.org/3.11/whatsnew/3.11.html#optimizations) f 字符串表达式 (2认同)

Dav*_*ers 15

作为旁注,您不必为了使用日志记录的新样式格式而受到性能影响.您可以传递任何对象logging.debug,logging.info实现了等__str__魔术方法.当日志记录模块确定它必须发出您的消息对象(无论它是什么)时,它会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))
Run Code Online (Sandbox Code Playgroud)

这些都在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.

  • 我希望我能更多地投票.它允许使用`format`进行日志记录而不会出现性能损失 - 通过覆盖`__str__`来精确地覆盖`logging`是为了 - 将函数调用缩短为单个字母(`N`),感觉非常类似于某些字母.定义字符串的标准方法 - AND允许惰性函数调用.谢谢!+1 (2认同)
  • 这与使用`logging.Formatter(style ='{')`参数的结果有什么不同? (2认同)

Jor*_*tao 10

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

'{type_names} [a-z]{2}'.format(type_names='triangle|square')
Run Code Online (Sandbox Code Playgroud)

加油IndexError.在这种情况下,您可以使用:

'%(type_names)s [a-z]{2}' % {'type_names': 'triangle|square'}
Run Code Online (Sandbox Code Playgroud)

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

  • 或者只使用`'{type_names} [az] {{2}}'.format(type_names ='triangle | square')`.这就像说`.format()`在使用已包含百分号的字符串时可以提供帮助.当然.你必须逃避他们. (3认同)
  • @Alfe你是对的,这就是为什么答案以“%可能有帮助的一种情况是当你格式化正则表达式时”开头的原因。具体来说,假设`a=r"[az]{2}"`是一个您将在两个不同的最终表达式中使用的正则表达式块(例如`c1 = b + a` 和`c2 = a`)。假设`c1` 需要进行`format` 处理(例如`b` 需要在运行时进行格式化),但`c2` 不需要。然后你需要 `a=r"[az]{2}"` 用于 `c2`,`a=r"[az]{{2}}"` 用于 `c1.format(...)`。 (2认同)

Syl*_*NFF 6

我要补充一点,从3.6版开始,我们可以像下面这样使用fstrings

foo = "john"
bar = "smith"
print(f"My name is {foo} {bar}")
Run Code Online (Sandbox Code Playgroud)

哪个给

我叫约翰·史密斯

一切都转换为字符串

mylist = ["foo", "bar"]
print(f"mylist = {mylist}")
Run Code Online (Sandbox Code Playgroud)

结果:

mylist = ['foo','bar']

您可以像其他格式一样传递函数

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

举个例子

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


小智 6

Python 3.6.7 对比:

#!/usr/bin/env python
import timeit

def time_it(fn):
    """
    Measure time of execution of a function
    """
    def wrapper(*args, **kwargs):
        t0 = timeit.default_timer()
        fn(*args, **kwargs)
        t1 = timeit.default_timer()
        print("{0:.10f} seconds".format(t1 - t0))
    return wrapper


@time_it
def new_new_format(s):
    print("new_new_format:", f"{s[0]} {s[1]} {s[2]} {s[3]} {s[4]}")


@time_it
def new_format(s):
    print("new_format:", "{0} {1} {2} {3} {4}".format(*s))


@time_it
def old_format(s):
    print("old_format:", "%s %s %s %s %s" % s)


def main():
    samples = (("uno", "dos", "tres", "cuatro", "cinco"), (1,2,3,4,5), (1.1, 2.1, 3.1, 4.1, 5.1), ("uno", 2, 3.14, "cuatro", 5.5),) 
    for s in samples:
        new_new_format(s)
        new_format(s)
        old_format(s)
        print("-----")


if __name__ == '__main__':
    main()
Run Code Online (Sandbox Code Playgroud)

输出:

new_new_format: uno dos tres cuatro cinco
0.0000170280 seconds
new_format: uno dos tres cuatro cinco
0.0000046750 seconds
old_format: uno dos tres cuatro cinco
0.0000034820 seconds
-----
new_new_format: 1 2 3 4 5
0.0000043980 seconds
new_format: 1 2 3 4 5
0.0000062590 seconds
old_format: 1 2 3 4 5
0.0000041730 seconds
-----
new_new_format: 1.1 2.1 3.1 4.1 5.1
0.0000092650 seconds
new_format: 1.1 2.1 3.1 4.1 5.1
0.0000055340 seconds
old_format: 1.1 2.1 3.1 4.1 5.1
0.0000052130 seconds
-----
new_new_format: uno 2 3.14 cuatro 5.5
0.0000053380 seconds
new_format: uno 2 3.14 cuatro 5.5
0.0000047570 seconds
old_format: uno 2 3.14 cuatro 5.5
0.0000045320 seconds
-----
Run Code Online (Sandbox Code Playgroud)

  • 您应该多次运行每个示例,单次运行可能会产生误导,例如操作系统通常很忙,因此代码的执行会延迟。请参阅文档:https://docs.python.org/3/library/timeit.html。(好头像,Guybrush!) (4认同)

Rou*_*han 5

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

s1='albha'
s2='beta'

f'{s1}{s2:>10}'

#output
'albha      beta'
Run Code Online (Sandbox Code Playgroud)


归档时间:

查看次数:

959655 次

最近记录:

6 年 前