Python几种字符串格式化方法及其性能比较

编程

add 0.4576963 # 加号拼接

%-formatting 0.37454160000000014 # % 格式化

str.format 0.44149049999999956 # .format 位置参数

str.format_kw 0.7051137000000001 # .format 关键字参数

f-string 0.2885597000000004 # f字符串

性能最好,且最易用的就是 f字符串

import timeit  

def add():

status = 200

body = "hello world"

return "Status: " + str(status) + "\r\n" + body + "\r\n"

def old_style():

status = 200

body = "hello world"

return "Status: %s\r\n%s\r\n" % (status, body)

def formatter1():

status = 200

body = "hello world"

return "Status: {}\r\n{}\r\n".format(status, body)

def formatter2():

status = 200

body = "hello world"

return "Status: {status}\r\n{body}\r\n".format(status=status, body=body)

def f_string():

status = 200

body = "hello world"

return f"Status: {status}\r\n{body}\r\n"

print("add", min(timeit.repeat(lambda: add())))

print("%-formatting", min(timeit.repeat(lambda: old_style())))

print("str.format", min(timeit.repeat(lambda: formatter1())))

print("str.format_kw", min(timeit.repeat(lambda: formatter2())))

print("f-string", min(timeit.repeat(lambda: f_string())))

以上是 Python几种字符串格式化方法及其性能比较 的全部内容, 来源链接: utcz.com/z/513968.html

回到顶部