[Tutor] Field Width

bob gailer bgailer at gmail.com
Thu Sep 19 15:48:47 CEST 2013


On 9/18/2013 12:50 PM, Jenny Allar wrote:
> I'm only a few days in to learning Python, so please bear with me.
That's what we are here for.
>
> I need to line up the decimals on the printed information but I cannot 
> get the text to look uniform at all.
Suggestions to help us help you.
- post only the relevant code. In this case that is:

     print("The cost of the carpet is $", format(subtotal,'9,.2f'))
     print("The flat fee is $", format(fee,'9,.2f'))
     print("The tax is $", format(tax_rate,'9,.2f'))
     print("The total due is $", format(total_due,'9,.2f'))

- When you get unexpected results post them as well.
- what OS are you using, version on Python, what are you using to write 
and run your code?

Now for the answer:

You have used tabs to align the text. This will often fail, as each 
output "window" has its own way of interpreting tabs.
Convert the tabs to spaces.

Even better provide formatting directives for the text as well as the 
number. I prefer Python's original format (%):
     print("%-30s$%9.2f" % ("The cost of the carpet is ", subtotal))

% start of first format specification
- = left justify
30 = field length
%s = treat value as string
$ = itself
% start of seconb format specification
9.2f = same meaning as in format()
% - format operator
("The cost of the carpet is ", subtotal) = tuple of values to be formatted.

HTH


-- 
Bob Gailer
919-636-4239
Chapel Hill NC

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20130919/f8ac89b8/attachment.html>


More information about the Tutor mailing list