如何在 python 中以良好的格式(垂直对齐)打印此信息?
How to print this information in a good format (vertical alignment) in python?
我试图让这些信息垂直对齐而不重叠。我只在每次迭代中使用了 print("\t xyz \t")
,它应该并排打印它,但有些字符串比其他字符串长。
How it is
How I want it
当前输出:
Ticker : GME
Employees : 14000
Title : CEO & Director Exec. VP & CFO Exec. VP & Chief Merchandising Officer
Name : Mr. George E. Sherman Mr. James Anthony Bell Mr. Chris R. Homeister
Ages : 58 52 51
Pay : 1,900,374 USD 801,318 USD 766,266 USD
通常这样做的方法是对每列的大小进行硬编码,或者 运行 通过数据,找到用于每列的列宽。
如果您想遍历并调整列宽,代码非常简单:
rows = [
["Ticker :", "GME"],
["Employees :", "14000"],
["Title :", "CEO & Director", "Exec. VP & CFO", "Exec. VP & Chief Merchandising Officer"],
["Name :", "Mr. George E. Sherman", "Mr. James Anthony Bell", "Mr. Chris R. Homeister"],
["Ages :", "58", "52", "51"],
["Pay :", "1,900,374 USD", "801,318 USD", "766,266 USD"],
]
# Build up a max length of each column
lengths = {}
for row in rows:
for i in range(len(row)):
lengths[i] = max(lengths.get(i, 0), len(row[i]))
for row in rows:
# For each cell, padd it by the max length
output = ""
for i in range(len(row)):
if len(output) > 0:
# Add a space between columns
output += " "
cell = row[i] + " " * lengths[i]
cell = cell[:lengths[i]]
output += cell
print(output)
这将输出:
Ticker : GME
Employees : 14000
Title : CEO & Director Exec. VP & CFO Exec. VP & Chief Merchandising Officer
Name : Mr. George E. Sherman Mr. James Anthony Bell Mr. Chris R. Homeister
Ages : 58 52 51
Pay : 1,900,374 USD 801,318 USD 766,266 USD
我试图让这些信息垂直对齐而不重叠。我只在每次迭代中使用了 print("\t xyz \t")
,它应该并排打印它,但有些字符串比其他字符串长。
How it is
How I want it
当前输出:
Ticker : GME
Employees : 14000
Title : CEO & Director Exec. VP & CFO Exec. VP & Chief Merchandising Officer
Name : Mr. George E. Sherman Mr. James Anthony Bell Mr. Chris R. Homeister
Ages : 58 52 51
Pay : 1,900,374 USD 801,318 USD 766,266 USD
通常这样做的方法是对每列的大小进行硬编码,或者 运行 通过数据,找到用于每列的列宽。
如果您想遍历并调整列宽,代码非常简单:
rows = [
["Ticker :", "GME"],
["Employees :", "14000"],
["Title :", "CEO & Director", "Exec. VP & CFO", "Exec. VP & Chief Merchandising Officer"],
["Name :", "Mr. George E. Sherman", "Mr. James Anthony Bell", "Mr. Chris R. Homeister"],
["Ages :", "58", "52", "51"],
["Pay :", "1,900,374 USD", "801,318 USD", "766,266 USD"],
]
# Build up a max length of each column
lengths = {}
for row in rows:
for i in range(len(row)):
lengths[i] = max(lengths.get(i, 0), len(row[i]))
for row in rows:
# For each cell, padd it by the max length
output = ""
for i in range(len(row)):
if len(output) > 0:
# Add a space between columns
output += " "
cell = row[i] + " " * lengths[i]
cell = cell[:lengths[i]]
output += cell
print(output)
这将输出:
Ticker : GME
Employees : 14000
Title : CEO & Director Exec. VP & CFO Exec. VP & Chief Merchandising Officer
Name : Mr. George E. Sherman Mr. James Anthony Bell Mr. Chris R. Homeister
Ages : 58 52 51
Pay : 1,900,374 USD 801,318 USD 766,266 USD