I'm afraid that it will be deprecated during the next Python versions
Don't be, str.format
does not appear (nor has a reason) to be leaving any time soon, the PEP that introduced f
prefixed-strings even states in its Abstract:
This PEP does not propose to remove or deprecate any of the existing string formatting mechanisms.
Formatted strings were introduced to address some of the shortcomings other methods for formatting strings had; not to throw the old methods away and force god-knows how many projects to use f-string's if they want their code to work for Python 3.6+.
As for the performance of these, it seems my initial suspicion that they might be slower is wrong, f-strings seem to easily outperform their .format
counterparts:
? cpython git:(master) ./python -m timeit -s "a = 'test'" "f'formatting a string {a}'"
500000 loops, best of 5: 628 nsec per loop
? cpython git:(master) ./python -m timeit "'formatting a string {a}'.format(a='test')"
100000 loops, best of 5: 2.03 usec per loop
These were done against the master branch of the CPython repository as of this writing; they are definitely subject to change:
f-strings
, as a new feature, might have possible optimizations
- Optimizations to CPython might make
.format
faster (e.g Speedup method calls 1.2x)
But really, don't worry about speed so much, worry about what is more readable to you and to others.
In many cases, that's going to be f-strings
, but there's some cases where format
is better.
与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…