float formatting

Tim Chase python.list at tim.thechases.com
Wed Jan 25 15:01:35 EST 2006


> for i in range(2,7):
>     print "|" + "%10.if" % num2 + "|"  #where i would be the iteration
> and the num of decimal places

	>>> for places in range(2,7):
	...     print "|%10.*f|" % (places, num2)
	...
	|     42.99|
	|    42.988|
	|   42.9877|
	|  42.98765|
	| 42.987654|

seems to do the trick.

It exploits the "*" operator for specifying the precision as 
detailed in item #4 at

http://docs.python.org/lib/typesseq-strings.html

which is the same as in C/C++ formatting strings.

-tkc









More information about the Python-list mailing list