1 |
Am Thu, 20 Sep 2012 05:05:11 -0400 |
2 |
schrieb Philip Webb <purslow@××××××××.net>: |
3 |
|
4 |
> 120919 Marc Joliet wrote: |
5 |
> > 120918 Philip Webb <purslow@××××××××.net> wrote: |
6 |
> >> With Python running as interpreter, I would get much more capability, |
7 |
> >> but I would need to enter the special line to load the math functions : |
8 |
> >> is it possible to do it with some capitalised variable in .bashrc , |
9 |
> >> which might list parameters telling Python3 what to load when it starts ? |
10 |
> >> one of the 'man' files seems to refer to something like that, but briefly. |
11 |
> > 3.) Put the "import" line in its own file and put it in the variable |
12 |
> > PYTHONSTARTUP, e.g. "export PYTHONSTARTUP=/path/to/my/script.py". |
13 |
> > Python executes it's contents before presenting the prompt, |
14 |
> > so you can put whatever imports you want in that script. |
15 |
> |
16 |
> Thanks, that's what I saw in my brief glance at the 'man'. |
17 |
> It works out of the box: the only problem is precision, |
18 |
> which at 16 decimal places is a bit more than I usually need (smile). |
19 |
> I can search out how to limit it to something more useful to me, |
20 |
> but might you have a quick answer ? Thanks for the above. |
21 |
|
22 |
Reading up the "format specification mini language" |
23 |
(http://docs.python.org/library/string.html#formatspec, and the format syntax |
24 |
explained above it), you could do as follows, to print as float rounded to four |
25 |
decimal places: |
26 |
|
27 |
print('{0:.4f}'.format(2.4)) |
28 |
|
29 |
Or, leaving out the zero (you only need the indexes if you print things out of |
30 |
order or multiple times): |
31 |
|
32 |
print('{:.4f}'.format(2.4)) |
33 |
|
34 |
Also, I re-remembered that there is an alternative formatting method (I don't |
35 |
print formatted output that often in python, I guess): |
36 |
|
37 |
print("%.4f" % 2.4) |
38 |
|
39 |
will do the same as the above two examples. Either way, to make things easy, |
40 |
you could define your own print function to do that for you, e.g.: |
41 |
|
42 |
def myprint(num, places=4, *args, **kargs): |
43 |
fmt_str = "{:." + str(places) + "f}" |
44 |
print(fmt_str.format(num), *args, **kargs) |
45 |
|
46 |
Using it would look like (in IPython): |
47 |
|
48 |
In [13]: myprint(2.4) |
49 |
2.4000 |
50 |
|
51 |
In [14]: myprint(2.4, 5) |
52 |
2.40000 |
53 |
|
54 |
You would put this in the startup script after the import line. Note that it |
55 |
passes extra positional and keyword arguments to print(), so you can specify a |
56 |
file to print to, for example. Also note that because of this, it won't work in |
57 |
Python 2. |
58 |
|
59 |
HTH |
60 |
-- |
61 |
Marc Joliet |
62 |
-- |
63 |
"People who think they know everything really annoy those of us who know we |
64 |
don't" - Bjarne Stroustrup |