如何设置对齐方式并限制 f 字符串中的字符长度?

问题描述 投票:0回答:1

我正在尝试从 CSV 阅读器输出一个包含三列的表格。每列的格式不同。第一列最多和最少 44 个字符。

这是打印语句:

print(f"{row[1] :<44s} | {row[2] :>5} | {row[0]} {i[0]}")

间距正确,但此语句允许超过 44 个字符。

python csv alignment
1个回答
0
投票

您可以通过数组切片轻松限制字符长度

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

© www.soinside.com 2019 - 2024. All rights reserved.