我计划使用string.format()使输出更具可读性。 我有姓名'和' BirthDate'和'薪水'列。
我收到了最广泛的字符串'姓名' (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:格式说明符无效
答案 0 :(得分:0)
你不能在{}
内直接写一个变量。这是正确的格式。
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
参考this。