Python numbers formatting [duplicate]

2020-04-08 12:45发布

问题:

This question already has answers here:
Closed 7 years ago.

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.

回答1:

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."



回答2:

%-style tends to be briefer, but also more limited. .format() has some advantages:

  1. allows user-defined classes to provide their own formatting flags,
  2. can access attributes of objects

though in your example with floats, neither of those is an advantage.

Both of these techniques will continue to work, so which you use is up to you. There had been an idea that %-formatting would be removed from Python 3, but that is no longer true. See the 3.2 docs:

As the new String Formatting syntax is more flexible and handles tuples and dictionaries naturally, it is recommended for new code. However, there are no current plans to deprecate printf-style formatting.