Python F-string 更快的格式化

Python的格式化有%s,format,F-string,下面是比较这三种格式化的速度比较

In [12]: a = 'hello'

In [13]: b = 'world'

In [14]: f'{a+b}'
Out[14]: 'helloworld'

In [16]: '%s'%(a+b)
Out[16]: 'helloworld'

In [17]: '{}'.format(a+b)
Out[17]: 'helloworld'

比较代码的运行时间

在ipython中用%timeit执行

In [18]: %timeit  f'{a+b}'
100000000 loops, best of 3: 14.9 ns per loop

In [19]: %timeit '%s'%(a+b)
The slowest run took 20.58 times longer than the fastest. This could mean that a
n intermediate result is being cached.
1000000 loops, best of 3: 211 ns per loop

In [21]: %timeit  '{}'.format(a+b)
The slowest run took 15.59 times longer than the fastest. This could mean that a
n intermediate result is being cached.
1000000 loops, best of 3: 329 ns per loop

通过比较运行时间,可以看出f-string 的运行时间最少

参考:
https://app.yinxiang.com/Home.action#n=e703271f-7479-4d87-8049-cd05b6bf72ea&ses=4&sh=2&sds=5&
https://www.pydanny.com/python-f-strings-are-fun.html
https://stackoverflow.com/questions/35745050/string-with-f-prefix-in-python-3-6

原文地址:https://www.cnblogs.com/Python666/p/7462635.html