提问人:Gregory St Germain 提问时间:9/18/2023 最后编辑:Gregory St Germain 更新时间:9/18/2023 访问量:75
如何在 f 字符串中设置对齐方式并限制字符长度?[复制]
How do I set alignment and restrict character length in an f string? [duplicate]
问:
这个问题在这里已经有答案了:
如何在 Python 中使用 str.format 截断字符串? (2 个答案)
2个月前关闭。
这篇文章在 2 个月前被编辑并提交审核,但未能重新打开帖子:
原始关闭原因未解决
我正在尝试从 CSV 阅读器输出一个包含三列的表。每列的格式都不同。第一列的最大和最小值为 44 个字符。
这是打印语句:
print(f"{row[1] :<44s} | {row[2] :>5} | {row[0]} {i[0]}")
间距正确,但此语句允许超过 44 个字符。
我得到的输出是这样的:
Wonders of the World | G | 16:40 20:00
Journey to Space | PG-13 | 19:00
Buffalo Bill And The Indians or Sitting Bull's History Lesson | PG | 15:00 19:30
Adventure of Lewis and Clark | PG-13 | 10:00 14:30
输出应如下所示:
Wonders of the World | G | 16:40 20:00
Journey to Space | PG-13 | 19:00
Buffalo Bill And The Indians or Sitting Bull | PG | 15:00 19:30
Adventure of Lewis and Clark | PG-13 | 10:00 14:30
答:
0赞
Brandon Pardi
9/18/2023
#1
您可以通过数组切片轻松限制字符长度
strr = 'Lorem Ipsum is simply dummy text of the printing and typesetting industry'
print(f"{strr[:44]} | {strr :>5}")
您将看到与第二列相比,第一列将限制长度的输出
Lorem Ipsum is simply dummy text of the prin | Lorem Ipsum is simply dummy text of the printing and typesetting industry
请注意,当您说第一列的最小值和最大值为 44 个字符时,有点不清楚,因此此答案适用于最多 44 个字符,但是可以轻松调整。
上一个:T-SQL 十进制除法精度
评论
.format
{}