简体   繁体   English

在多行打印python 3.x中显示变量的值

[英]Displaying the value of a variable within a multi line print python 3.x

I am trying to print out a multi line statement and have variables be displayed within the print. 我正在尝试打印多行语句,并在打印中显示变量。 My code is looks as follows: 我的代码如下所示:

snacks = ['twix','twix','twix','twix']

t = snacks.count('twix')

def stock(x):
    print('''

    Snack    Stock
    -------------
    Twix:     x

''')

I want the value of t to show where I put the variable into the multi-line print where calling 我想让t的值显示我将变量放入多行打印的位置,在哪里调用

stock(t)

Gives me: 给我:

    Snack    Stock
    -------------
    Twix       4

Thanks for the help! 谢谢您的帮助!

You can do this 你可以这样做

snacks = ['twix','twix','twix','twix']

t = snacks.count('twix')

def stock(x):
    print("Snack    Stock")
    print("-------------")
    print("Twix:     %d"% (t))

stock(t)

You can print \\n to print new line,and use str.format to format your string: 您可以打印\\n以打印新行,并使用str.format格式化字符串:

'<' 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. '^'强制字段在可用空间内居中。

snacks = ['twix','test','twix','example']

t = snacks.count('twix')
print("Snack    Stock    \n-------------")

from collections import Counter
for k,v in Counter(snacks).items():
    print('{:<9}    {:<9}'.format(k,v))

Output: 输出:

Snack    Stock    
-------------
test         1        
twix         2        
example      1    

See more details from Format String Syntax . 请参阅“ 格式字符串语法”中的更多详细信息。

Hope this helps. 希望这可以帮助。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM