[Tutor] Help - want to display a number with two decimal places
alan.gauld at btinternet.com
Sat Mar 5 10:35:17 CET 2011
"Modulok" <modulok at gmail.com> wrote
> However, to make all of your numbers line up nicely, regardless of
> long they are, you need to look into advanced string formatting via
> the builtin string method 'format()'. It takes a little practice
Or, if your version of Python doesn't support string.format() (pre
you can use \t characters to insert tabs and provide a field length
value in the format string and use - signs for string alignment.
If you need more you can do double formatting where you use
an initial format string to create the output values then insert
those into the final output string.
The new format() method is more powerful in these jinds of situation
(although sadly still not as powerful as COBOLs "picture" feature
So your strings might look like:
> # First prints the first argument (the 0th index) to 'format(),
> # left aligned '<', and 18 characters wide, whitespace padded.
> # Then prints the second argument, (the 1st index) right aligned,
> # also 18 characters wide, but the second argument is specified
> # be a float 'f', that has a precision of 2 decimal places, '.2'.
print "%-18.0s\t%18.2f" %(....)
Author of the Learn to Program web site
More information about the Tutor