Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Python numbers formatting [duplicate]

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.

like image 555
Vassilis Avatar asked Dec 27 '22 22:12

Vassilis


1 Answers

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

like image 90
Levon Avatar answered Jan 05 '23 16:01

Levon