Displaying the value of a variable within a multi line print python 3.x
我正试图打印出一个多行语句,并在打印中显示变量。我的代码如下:
| 1 2 3 4 5 6 7 8 9 10 11 12 | snacks = ['twix','twix','twix','twix'] t = snacks.count('twix') def stock(x): print(''' Snack Stock ------------- Twix: x ''') | 
我想让t值显示我把变量放在多行打印中调用的位置
| 1 | stock(t) | 
给我:
| 1 2 3 |     Snack    Stock ------------- Twix 4 | 
谢谢你的帮助!
您可以打印
'<' Forces the field to be left-aligned within the available space '>' Forces the field to be right-aligned within the available space
'^' Forces the field to be centered within the available space.
| 1 2 3 4 5 6 7 8 9 | snacks = ['twix','test','twix','example'] t = snacks.count('twix') print("Snack Stock -------------") from collections import Counter for k,v in Counter(snacks).items(): print('{:<9} {:<9}'.format(k,v)) | 
输出:
| 1 2 3 4 5 | Snack    Stock     ------------- test 1 twix 2 example 1 | 
请参阅格式字符串语法中的更多详细信息。
希望这有帮助。
你可以做到这一点
| 1 2 3 4 5 6 7 8 9 10 | snacks = ['twix','twix','twix','twix'] t = snacks.count('twix') def stock(x): print("Snack Stock") print("-------------") print("Twix: %d"% (t)) stock(t) |