如何在python中生成固定大小的格式化字符串?

2024-09-29 02:20:17 发布

您现在位置:Python中文网/ 问答频道 /正文

我想创建一个固定大小和字段之间固定位置的格式化字符串。一个例子解释得更好,这里有3个明显不同的字段,字符串的大小是固定的:

XXX        123   98.00
YYYYY        3    1.00
ZZ          42  123.34

如何在python(2.7)中对字符串应用这种格式?


Tags: 字符串格式例子xxxzzyyyyy
1条回答
网友
1楼 · 发布于 2024-09-29 02:20:17

当然,使用.format方法。E、 g

print '{:10s} {:3d}  {:7.2f}'.format('xxx', 123, 98)
print '{:10s} {:3d}  {:7.2f}'.format('yyyy', 3, 1.0)
print '{:10s} {:3d}  {:7.2f}'.format('zz', 42, 123.34)

将打印

xxx        123    98.00
yyyy         3     1.00
zz          42   123.34

您可以根据需要调整字段大小。注意,.format独立于print来格式化字符串。我只是用打印来显示字符串。简要说明:

10s format a string with 10 spaces, left justified by default

3d format an integer reserving 3 spaces, right justified by default

7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.

有许多附加选项可以定位/格式化字符串(填充、左/右对齐等),String Formatting Operations将提供更多信息。

相关问题 更多 >