Possible Duplicate:
String formatting options: pros and cons
What's the difference between
"%.2f" % x
and
"{:.2f}".format(x)
I am a bit confused about which method should I use and for which version of Python.
In general you want to use the 2nd form (.format()
) it's newer and the other one will eventually go away (at least that was the intention at some point - see Notes below).
To quote the Python What’s New In Python 3.0 docs:
A new system for built-in string formatting operations replaces the % string formatting operator. (However, the % operator is still supported; it will be deprecated in Python 3.1 and removed from the language at some later time.) Read PEP 3101 for the full scoop.
.format()
has been available since at least Python 2.6
More information about Advanced String Formatting (PEP 3101)
Notes:
@Duncan also mentions a reference to a thread that discusses whether/when the %
based formatting will go away in the comments below. And @NedBatchelder has this definite quote from the Python 3.2 docs: "... there are no current plans to deprecate printf-style formatting.
"
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With