简体   繁体   中英

%precision 2 on Python

If I have this piece of code:

import csv

%precision 2

with open('blah.csv') as csvfile:
    blah = list(csv.DictReader(csvfile))

What does it means the %precision 2 line?

This is an IPython magic. It controls how floats display:

>>> 1.2345
1.2345
>>> %precision 2
'%.2f'
>>> 1.2345
1.23

Documented here .

Note : It suggests your script was intended to be executed within an IPython runtime (such as a notebook ). In a regular Python interpreter that will be a syntax error.

This is to set a floating point precision for printing. It sets the floating point to 2 decimal points. This doesn't work in all interpreters though, but it does work in Jupyter-Notebook.

NB: Thanks to Chrisz for the point.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM