2015-03-25 76 views
0

如何在一列中打印這些功能。如何在列中打印列表?

item = stock.stock_list(location_name) 



for x in sorted(item): 
    """Stock list of given location""" 
    print (x) 

for y in sorted(item): 
    """Stock price of give location and stock list""" 
    print ("{0:.2f}".format(stock.stock_price(y))) 

for z in sorted(item): 
    """stock qty of given location name and item""" 
    print(stock.stock_quantity(location_name, z))  

輸出是

Elephant foot yam 
Kai-lan  
16.25 
13.96 
90 
18 

希望它是

Elephant foot yam   16.25    90 
Kai-lan     13.96    18 

第一個必須被左對齊和20寬,所述第二被右對齊和8寬和第三右對齊,6寬。


也是另外一個問題。

如何從括號內的下方打印location_id?

print(toptext, location_name, location_id) 

輸出是

Stock summary for location 123456789 

我希望它是

Stock summary for Wellington (123456789) 

我累

print(toptext, location_name, "(", location_id ,")") 

但像這樣的括號之間的空間(123456789)

預先感謝您

+0

在問題的第二部分,您的目標是在那裏沒有「位置」,而是「惠靈頓」嗎?那麼它是一個錯誤,位置不是由實際位置取代?如果是這樣,您需要深入瞭解location_name的設置方式。 – syntonym 2015-03-25 10:10:32

回答

0

對於第二個問題試試這個:如果你要打印更多的變量,你可以做這樣的

print "(%s)" % location_id 

print "%s %s (%s)" % (toptext, location_name, location_id) 
0

與第一部分的問題,您需要在每個循環中打印一整行

for x in sorted(item): 
    """Stock list of given location""" 
    print (x) 
    print (spacing) 
    """Stock price of give location and stock list""" 
    print ("{0:.2f}".format(stock.stock_price(y))) 
    print (spacing) 
    """stock qty of given location name and item""" 
    print(stock.stock_quantity(location_name, z)) 

敷設出來更好,Python的讓你做「」 * N 這樣你就可以計算的行中的每個單元之間所需的空間數量,做一些這樣的:

" " * (spacing_length - len(cell)) 
-1

可以archieve所有以format()函數。

你的第一個問題是:

"{:<20}{:>8.2f}{:>6}".format(item, price, stock) 

在你的第二個問題應該是

"{} {} ({})".format(toptext, location_name, location_id) 

欲瞭解更多信息,請閱讀格式的文檔。