0

experienced developers and Python experts.

I'm just learning Python.

number = ['No.', 1  , 2  , 3 , 4 , 5 , 6]
company =['Company' , 'Microsoft' , 'Amazon' , 'Paypal' , 'Apple' , 'Fastly' , 'Square']
cap = ['Cap' , 'Mega' , 'Mega' , 'Large' , 'Large' , 'Mid' , 'Mid']
qty = ['Qty', '100' , '5' , '80' , '100' , '30' , '30']
bought_price = ['Bought Price' , '188' , '1700' , '100' , '60' , '40' , '40']
market_price = ['Market Price' , '207' , '3003' , '188' , '110' , '76' , '178' ]

for a,b,c,d,e,f in zip(number, company, cap,qty,bought_price, market_price ): 
    print(a, '\t' , b , '\t' , c , '\t' , d , '\t' , e , '\t' , f)

output:

    No.      Company         Cap     Qty     Bought Price    Market Price
    1        Microsoft       Mega    100     188     207
    2        Amazon          Mega    5       1700    3003
    3        Paypal          Large   80      100     188
    4        Apple   Large   100     60      110
    5        Fastly          Mid     30      40      76
    6        Square          Mid     30      40      178

Please help me figure out what I did wrong.

alani
  • 12,573
  • 2
  • 13
  • 23
  • Hello and welcome to StackOverflow! What's the problem with your output? – Daniel Walker Dec 03 '21 at 02:39
  • 5
    `\t` does not guarantee alignment in a tabular output. In your example anything longer than `Apple` causes `\t` to jump to the next tab stop. Use a proper method for outputting tabular data: https://stackoverflow.com/questions/9535954/printing-lists-as-tabular-data – Selcuk Dec 03 '21 at 02:41
  • The `Bought Price` column header is wide enough that the next column of numbers needs two tabs, not one. – John Gordon Dec 03 '21 at 02:42

1 Answers1

0

I get what you wanted to do, unfortunately the use of tab is a bit inconsitent when printing.

What I typically do is use f-string to format alignments. The basic syntax of the f-string is f"{(variable):(leftcenterrightALIGNMENT)(NUMOFCHARACTERS)(datatype)}"

For example printing a left indented string with 15 characters worth (will be padded if the string is less than the 15 char max) is print(f"{'MYSTRING':<15s}")

Here is a good guide for you to check out: https://realpython.com/python-f-strings/

As for your code, here is an example on how to apply f-string with your code.

number = ['No.', 1  , 2  , 3 , 4 , 5 , 6]
company =['Company' , 'Microsoft' , 'Amazon' , 'Paypal' , 'Apple' , 'Fastly' , 'Square']
cap = ['Cap' , 'Mega' , 'Mega' , 'Large' , 'Large' , 'Mid' , 'Mid']
qty = ['Qty', '100' , '5' , '80' , '100' , '30' , '30']
bought_price = ['Bought Price' , '188' , '1700' , '100' , '60' , '40' , '40']
market_price = ['Market Price' , '207' , '3003' , '188' , '110' , '76' , '178' ]

for a,b,c,d,e,f in zip(number, company, cap,qty,bought_price, market_price ): 
    #print(f"{a:4}"a, '\t' , b , '\t' , c , '\t' , d , '\t' , e , '\t' , f)
    print(f"{str(a):<15s} {str(b):<15s} {str(c):<15s} {str(d):<15s} {str(e):<15s} {str(f):<15s}")
Kurt Rojas
  • 319
  • 2
  • 12