Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String formatting: Columns in line

Tags:

I am trying to format the string so everything lines up between the two.

APPLES                           $.99                           214                        kiwi                             $1.09                           755  

I am trying this by doing:

fmt = ('{0:30}{1:30}{2:30}'.format(Fruit,price,qty)) 

How would I get a column to line up? I read the docs but I am confused. I was thinking that the {1:30} would make it 30 spaces, then it would print the next item, but it appears that it is 30 spaces from where the previous item ended.

Thanks

like image 639
Trying_hard Avatar asked Sep 30 '13 20:09

Trying_hard


People also ask

How do you format a line in Java?

In Windows, a new line is denoted using “\r\n”, sometimes called a Carriage Return and Line Feed, or CRLF. Adding a new line in Java is as simple as including “\n” , “\r”, or “\r\n” at the end of our string.

What is .2f in Python?

2f means to round up to two decimal places. You can play around with the code to see what happens as you change the number in the formatter.


2 Answers

str.format() is making your fields left aligned within the available space. Use alignment specifiers to change the alignment:

'<' Forces the field to be left-aligned within the available space (this is the default for most objects).

'>' Forces the field to be right-aligned within the available space (this is the default for numbers).

'=' Forces the padding to be placed after the sign (if any) but before the digits. This is used for printing fields in the form ‘+000000120’. This alignment option is only valid for numeric types.

'^' Forces the field to be centered within the available space.

Here's an example (with both left and right alignments):

>>> for args in (('apple', '$1.09', '80'), ('truffle', '$58.01', '2')): ...     print '{0:<10} {1:>8} {2:>8}'.format(*args) ... apple         $1.09       80 truffle      $58.01        2 
like image 145
Steven Rumbalski Avatar answered Jan 17 '23 01:01

Steven Rumbalski


With python3 f-strings (not your example but mine):

alist = ["psi", "phi", "omg", "chi1", "chi2", "chi3", "chi4", "chi5", "tau"] for ar in alist:     print(f"{ar: >8}", end=" ") print() for ar in alist:     ang = ric.get_angle(ar)     print(f"{ang:8.4}", end=" ") print() 

generates

  psi      phi      omg     chi1     chi2     chi3     chi4     chi5      tau  4.574   -85.28    178.1   -62.86   -65.01   -177.0    80.83    8.611    115.3  
like image 23
robm Avatar answered Jan 16 '23 23:01

robm