f-string 句法和 % 操作符 性能比较


% 操作符比 f-string Syntax 慢,但经常使用。

f-string 句法可用于格式化字符串文字,由 CPython 3.6 引入。

性能比较


f-string 采用 f 或 F 作前缀,与 + 和 % 操作符的性能比较如下:

from datetime import datetime
start = datetime.now()
count = 2000000
while count:
    count -= 1
    a = "str" + "ing"
    b = a + " test"
print(datetime.now() - start)
 
start = datetime.now()
count = 2000000
while count:
    count -= 1
    a = "%sing" % ("str")
    b = "%s test" % (a)
print(datetime.now() - start)
 
start = datetime.now()
count = 2000000
while count:
    count -= 1
    string = "str"
    a = f"{string}ing"
    b = f"{a} test"
print(datetime.now() - start)
					

by Digital IDE 运行调试, 获取以下结果。

0:00:01.061802
0:00:02.395206
0:00:01.809603
					

其中 + 内置操作符用时最少,但必须是 str 对象类型;f-string 句法次之,% 操作符最慢。

左对齐


左对齐是在 %s 之间添加 - 号和字符位数,如下所示:

>>> "%-5s" % (6)
'6    '
>>>
					

右对齐


右对齐是在 %s 之间添加 + 号和字符位数,如下所示:

>>> "%+5s" % (6)
'    6'
>>>
					

See also:

% Operator

Format String Syntax

Format String Literal

Copyright Notice: This article is exclusive original manuscripts, copyrighted by Happy Digits Software , shall not be reproduced without permission.

Table of contents

  1. 左对齐
  2. 右对齐

Previous topic

format() Method

Next topic

f-string Usage

Quick search