Python 2.6 introduced the str.format() method with a slightly different syntax from the existing % operator. Which is better and for what situations?
Python 3.6 has now introduced another string formatting format of string literals (aka "f" strings) via the syntax f"my string". Is this formatting option better than the others?
The following uses each method and has the same outcome, so what is the difference?
#!/usr/bin/python sub1 = "python string!" sub2 = "an arg"
sub_a = "i am a %s" % sub1 sub_b = "i am a {0}".format(sub1) sub_c = f"i am a {sub1}"
arg_a = "with %(kwarg)s!" % {'kwarg':sub2} arg_b = "with {kwarg}!".format(kwarg=sub2) arg_c = f"with {sub2}!"
print(sub_a) # "i am a python string!" print(sub_b) # "i am a python string!" print(sub_c) # "i am a python string!"
print(arg_a) # "with an arg!" print(arg_b) # "with an arg!" print(arg_c) # "with an arg!" Furthermore when does string formatting occur in Python? For example, if my logging level is set to HIGH will I still take a hit for performing the following % operation? And if so, is there a way to avoid this?
log.debug("some debug info: %s" % some_info)
I'd say use one of the latter two at your preference, just be consistent.
I think the f-strings are usually a bit shorter, just be careful to not expose something by accident when you intend literal {...}.
sairamuppugundla - If you format your question to use syntax highlighting, it will be more readable.
TL;DR: I use f-Strings where I can
First of all python2 is end of life, so when possible use python3
If you have an option, use latest python version.
As you have already mentioned, f-strings are supported in python 3.6 onward. But PyPI package f2format allows you to use it with python 3.3 onward.
Finally this might answer your question more directly (and better than I did)
Sébastien Portebois
Software architect at Ubisoft
I’m late on this one, but since this question comes quite frequently in our teams too:
rule of thumbs: use f-strings if you’re sure all your users will support it (i.e. if you create a package, then the lowest version you support might be a criteria here)
But if you can, f-strings are shorter, easier to read, and faster at runtime. There’s no good reason to not use them whenever you can. (re the speed, I don’t have the links here, but google will give you benchmarks about it)
The only time I switch back to the .format() stuff is when them we need to build templates dynamically.