我计划使用 string.format() 使输出更具可读性。我有“姓名”和“出生日期”和“工资”列。
我得到了最宽的字符串“Name”(widest_name = 5)和最宽的字符串“BirthDate”(widest_birthDate = 16)。
我的日期设置: data_set = [["Dan", "August 8 1954", "50k"], ["Jason", "December 26 1984", "90k"], ...]
我想要字符串格式(.format() 方法)和你最广泛的 Name 和 BirthDate。
输出:
Name BirthDate Salary
Dan August 8 1954 50k
Jason December 26 1984 90k
我的代码:
print("{0: <widest_name }, {1: <widest_birthDate }, 'Salary'".format("Name", "BirthDate"))
for lists in data_set :
print(lists[0], lists[1], lists[2])
但我收到错误:builtins.ValueError: Invalid format specifier
你不能直接在里面写一个变量{}
。这是正确的格式。
data_set = [["Dan", "August 8 1954", "50k"], ["Jason", "December 26 1984", "90k"]]
widest_name = 5
widest_birthDate = 16
print("{:<{width_name}} {:<{width_date}} {}".format("Name", "BirthDate","Salary",width_name=widest_name,width_date=widest_birthDate))
for lists in data_set :
print("{:<{width_name}} {:<{width_date}} {}".format(lists[0], lists[1], lists[2],width_name=widest_name,width_date=widest_birthDate))
Name BirthDate Salary
Dan August 8 1954 50k
Jason December 26 1984 90k
参考这个。
本文收集自互联网,转载请注明来源。
如有侵权,请联系[email protected] 删除。
我来说两句