2024-09-29 02:20:17 发布
网友
我想创建一个固定大小和字段之间固定位置的格式化字符串。一个例子解释得更好,这里有3个明显不同的字段,字符串的大小是固定的:
XXX 123 98.00 YYYYY 3 1.00 ZZ 42 123.34
如何在python(2.7)中对字符串应用这种格式?
当然,使用.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来格式化字符串。我只是用打印来显示字符串。简要说明:
.format
print
10s format a string with 10 spaces, left justified by default3d format an integer reserving 3 spaces, right justified by default7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.
10s format a string with 10 spaces, left justified by default
10s
3d format an integer reserving 3 spaces, right justified by default
3d
7.2f format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.
7.2f
有许多附加选项可以定位/格式化字符串(填充、左/右对齐等),String Formatting Operations将提供更多信息。
当然,使用.format方法。E、 g
将打印
您可以根据需要调整字段大小。注意,
.format
独立于print
来格式化字符串。我只是用打印来显示字符串。简要说明:有许多附加选项可以定位/格式化字符串(填充、左/右对齐等),String Formatting Operations将提供更多信息。
相关问题 更多 >
编程相关推荐