我正在尝试提高我的Python技能,列表和列表格式。我一直在网上做一些练习,但遇到了我似乎无法解决的问题。
# [ ] The list `data` contains personnel information (Name, ID, email)
# Write a program using Python-style formatting to print out the data as
follows:
'''
Name | ID | Email
________________________________________________________
Suresh Datta | 57394 | suresh@example.com
Colette Browning | 48539 | colette@example.com
Skye Homsi | 58302 | skye@example.com
Hiroto Yamaguchi | 48502 | hiroto@example.com
Tobias Ledford | 48291 | tobias@example.com
Jin Xu | 48293 | jin@example.com
Joana Dias | 23945 | joana@example.com
Alton Derosa | 85823 | alton@example.com
'''
data = [
["Suresh Datta", 57394, "suresh@example.com"]
, ["Colette Browning", 48539, "colette@example.com"]
, ["Skye Homsi", 58302, "skye@example.com"]
, ["Hiroto Yamaguchi", 48502, "hiroto@example.com"]
, ["Tobias Ledford", 48291, "tobias@example.com"]
, ["Tamara Babic", 58201, "tamara@example.com"]
, ["Jin Xu", 48293, "jin@example.com"]
, ["Joana Dias", 23945, "joana@example.com"]
, ["Alton Derosa", 85823, "alton@example.com"]
]
我设法解决了其他问题,但这是我唯一不知道怎么做的人。任何帮助表示赞赏。谢谢!
答案 0 :(得分:1)
使用Python 3.6+ f字符串:
data = [["Suresh Datta", 57394, "suresh@example.com"],
["Colette Browning", 48539, "colette@example.com"],
["Skye Homsi", 58302, "skye@example.com"],
["Hiroto Yamaguchi", 48502, "hiroto@example.com"],
["Tobias Ledford", 48291, "tobias@example.com"],
["Tamara Babic", 58201, "tamara@example.com"],
["Jin Xu", 48293, "jin@example.com"],
["Joana Dias", 23945, "joana@example.com"],
["Alton Derosa", 85823, "alton@example.com"]]
print(f'{"Name":^21}|{"ID":^12}|{"Email":^21}')
print('_'*56)
for name,id,email in data:
print(f'{name:^21}|{id:^12}|{email:>21}')
输出:
Name | ID | Email
________________________________________________________
Suresh Datta | 57394 | suresh@example.com
Colette Browning | 48539 | colette@example.com
Skye Homsi | 58302 | skye@example.com
Hiroto Yamaguchi | 48502 | hiroto@example.com
Tobias Ledford | 48291 | tobias@example.com
Tamara Babic | 58201 | tamara@example.com
Jin Xu | 48293 | jin@example.com
Joana Dias | 23945 | joana@example.com
Alton Derosa | 85823 | alton@example.com
在f字符串中,字段为{content:format}
。要打印标题,文字字符串是内容,例如{"Name":^21}
的意思是“写一个以21个字符为中心的Name
。要打印内容{email:>21}
的主语“将变量email
的值写在一个右对齐的21个字符中字段。
答案 1 :(得分:0)
print('{:^30} |{:^30}|{:^30}' .format("Name","ID","Email"))
print('_'*90)
for s in data:
print('{:^30} |{:^30}|{:^30}' .format(s[0],s[1],s[2]))
输出
Name | ID | Email
__________________________________________________________________________________________
Suresh Datta | 57394 | suresh@example.com
Colette Browning | 48539 | colette@example.com
Skye Homsi | 58302 | skye@example.com
Hiroto Yamaguchi | 48502 | hiroto@example.com
Tobias Ledford | 48291 | tobias@example.com
Tamara Babic | 58201 | tamara@example.com
Jin Xu | 48293 | jin@example.com
Joana Dias | 23945 | joana@example.com
Alton Derosa | 85823 | alton@example.com