如何在 f 字符串中设置对齐方式并限制字符长度?[复制]

How do I set alignment and restrict character length in an f string? [duplicate]

提问人:Gregory St Germain 提问时间:9/18/2023 最后编辑:Gregory St Germain 更新时间:9/18/2023 访问量:75

问:

这个问题在这里已经有答案了:
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
Python 对齐 方式字符串格式截

评论

0赞 Jesse Sealand 9/18/2023
你会发布一个问题输出是什么样子以及它应该是什么样子的示例吗?我不完全确定你的意思。
0赞 Community 9/18/2023
请澄清您的具体问题或提供其他详细信息以准确说明您的需求。正如目前所写的那样,很难确切地说出你在问什么。
0赞 Karl Knechtel 9/18/2023
在 f 字符串中执行此操作的方式与在普通字符串上调用方法时相同,因为它们使用相同的语法来描述每个占位符的格式(f 字符串允许对占位符中的内容进行更复杂的计算,但其格式相同)。请参阅链接的副本。.format{}

答:

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 个字符,但是可以轻松调整。