Python number formatting

Possible duplicate:
String formatting options: pros and cons

What is the difference between

"%.2f" % x 

and

 "{:.2f}".format(x) 

I'm a little confused about which method to use and for which version of Python.

+4
source share
2 answers

In general, you want to use the second form ( .format() ), it is new and the other will eventually leave (at least that was the intention at some point - see Notes below).

To quote Python What's new in Python 3.0 docs:

The new system for embedded 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 a later time.) Read PEP 3101 for a complete scoop.

.format() is available since at least Python 2.6

Additional Information about Advanced String Formatting (PEP 3101)

Notes:

@Duncan also mentions a stream link that discusses whether / when % -based formatting will disappear in the comments below. And @NedBatchelder has this specific quote from Python 3.2 docs : " ... there are no current plans to deprecate printf-style formatting. "

+7
source

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

  • allows custom classes to provide their own formatting flags,
  • can access object attributes

although in your example with floats none of them is an advantage.

Both of these methods will continue to work, so you are using exactly what you need. There was an idea that% formatting would be removed from Python 3, but this is no longer the case. See 3.2 docs :

Since the new string formatting syntax is more flexible and naturally uses tuples and dictionaries, it is recommended for new code. However, there are currently no plans to abandon printf-style formatting.

+3
source

Source: https://habr.com/ru/post/919243/


All Articles