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
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:
'<' 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.