python-3.x - 在显示期间对字典内列表中的字符串值进行文本换行
问题描述
我有一本像下面这样的字典,但我在尝试对以下内容进行文本换行时遇到了麻烦:
dict= { 'ProductA' : ['2020-08-03 16:26:21', 'This painting was done by XNB.The artist seeks to portray the tragedies caused by event XYZ. The painting weighs 2kg.'], 'ProductB':['2020-08-03 16:26:21','This painting is done by ONN.This painting is done by ONN.Decades later, it was discovered in the black market of country XYZ.It was bought for 2 million dollars by ABC.']}
字典显示的期望结果:
Product Name Last Edited Information
Product A 2020-08-03 16:26:21 This painting was done by XNB.The artist
seeks to portray the tragedies caused by
event XYZ. The painting weighs 2kg.
Product B 2020-08-03 16:26:21 This painting is done by ONN.This painting
is done by ONN.Decades later, it was
discovered in the black market of country
XYZ.It was bought for 2 million dollars
by ABC.
下面是我尝试输出上述显示:
from textwrap import wrap
print("{:<25} {:<30} {:<10}".format('Product Name','Last Edited','Information'))
for product_name, data in dict.items():
last_edit, info = data
wrapped_info=wrap(info, 45)
print("{:<25} {:<30} {:<10}".format(product_name, last_edit, wrapped_info))
#TypeError:传递给列表的格式字符串不受支持。格式
我不太明白错误想说什么。我哪里出错了,我应该如何编码以获得所需的输出?
解决方案
您的代码中的问题是wrap()
返回字符串列表。您需要使用 将结果转换wrap()
为字符串join()
。
尝试这个:
from textwrap import wrap
d = { 'ProductA' : ['2020-08-03 16:26:21', 'This painting was done by XNB.The artist seeks to portray the tragedies caused by event XYZ. The painting weighs 2kg.'], 'ProductB':['2020-08-03 16:26:21','This painting is done by ONN.This painting is done by ONN.Decades later, it was discovered in the black market of country XYZ.It was bought for 2 million dollars by ABC.']}
print("{:<25} {:<30} {:<10}".format('Product Name','Last Edited','Information'))
for product, data in d.items():
date, info = data
wrapped_info = f'\n{" " * (25 + 30 + 2)}'.join(wrap(info, 45))
print("{:<25} {:<30} {:<10}\n".format(product, date, wrapped_info))
输出:
Product Name Last Edited Information
ProductA 2020-08-03 16:26:21 This painting was done by XNB.The artist
seeks to portray the tragedies caused by
event XYZ. The painting weighs 2kg.
ProductB 2020-08-03 16:26:21 This painting is done by ONN.This painting is
done by ONN.Decades later, it was discovered
in the black market of country XYZ.It was
bought for 2 million dollars by ABC.
推荐阅读
- c# - 对于简单的提取/转换/加载任务,我应该使用哪种类型的项目?
- batch-file - 可以在 FOR 循环中对文件进行排序/排序吗?
- python - 如何让 Graphviz 垂直而不是水平显示图表?
- c++ - g++ std::filesystem::last_write_time 中的重大更改
- python - 使用 Python 从 SQL Server 中的两个表中查询
- vb.net - 将 DataGridViewComboBoxColumn 绑定到 SQL 数据源
- python - Pandas 中的 Vlookup - 加入还是合并?
- delphi - 将 TForm 分配给一个变量 Delphi 以在其他单元中使用
- android - 如何“提交符合政策的更新”?
- php - 如何使用 Prestashop 使用 PHP 上传图片?