Convert old string substitutions to f-strings in term.py by ashleysommer · Pull Request #2864 · RDFLib/rdflib (original) (raw)
I thought this work had already been done around 18 months ago.
Or maybe there was and old PR that does it? I'm not sure.
As-of Python 3.8, f-strings are feature-comparable with str.format()
, and have even eventually surpassed the raw performance of old-style "%-substitution" strings from the Python2 days.
import timeit
joining two string variables
t0 =timeit.timeit('a+b', setup='a,b = "", "abcd13"*1000') print(t0) t1 =timeit.timeit('"%s%s" % (a, b)', setup='a,b = "", "abcd13"*1000') print(t1) t2 = timeit.timeit('f"{a}{b}"', setup='a,b = "", "abcd13"*1000') print(t2) t3 = timeit.timeit('f"{b}"', setup='b = "abcd13"*1000') print(t3)
joining three strings
t0 =timeit.timeit('a+b+c', setup='a,b,c = "", "abcd13"*1000, ""') print(t0) t1 =timeit.timeit('"%s%s%s" % (a, b, c)', setup='a,b,c = "", "abcd13"*1000, ""') print(t1) t2 = timeit.timeit('f"{a}{b}{c}"', setup='a,b,c = "", "abcd13"*1000, ""') print(t2)
Wrapping a variable with prefix and suffix
t3 = timeit.timeit('f"{b}"', setup='b = "abcd13"*1000') print(t3)
two string variables
0.08020864403806627 # Concat with + is fastest for 2 (and only 2) values 0.08790699497330934 0.08184163994155824 0.08165007410570979
joining three strings
0.15257811499759555 0.09559847600758076 0.08691176993306726 # f-string concat is fastest for unknown 3 variables. 0.08586340001784265 # Inline f-string substitution is fastest for wrapped variables.