[英]Python Print Formatting
dict={'algorithm':'user1','datastr':'user2','hashing':'user3'}
def forums(dict):
header = ("SubForums","Created By")
dict_list=dict.items()
dict_list.insert(0,header)
i=0
col_width = max(len(word) for row in dict_list for word in row) + 2 # padding
for row in dict_list:
print str(i+1)+"."+"".join(word.ljust(col_width) for word in row)
我想像這樣打印:
SubForums Created By
1.Algorithm User1
2.Hash user2
3.datastr user3
它目前打印像dis:
1.SubForums Created By
2.Algorithm User1
3.Hash user2
4.datastr user3
任何人都可以請更正我的代碼並幫助我。 先感謝您。
def forums(d):
dict_list = [('Subforums', 'Created by')]
for i, (k, v) in enumerate(d.items(), 1):
k = '{0}. {1}'.format(i, k)
dict_list.append((k, v))
col_width = max(len(word) for row in dict_list for word in row) + 2 # padding
for row in dict_list:
print ''.join(word.ljust(col_width) for word in row)
(注意我是如何將dict
更改為d
:使用內置函數的名稱作為變量是一個壞主意!)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.