This question already has an answer here:
这个问题在这里已有答案:
- How to format print output or string into fixed width? 4 answers
- 如何将打印输出或字符串格式化为固定宽度? 4个答案
I want to create a formatted string with fixed size with fixed position between fields. An example explains better, here there are clearly 3 distinct fields and the string is a fixed size:
我想创建一个固定大小的格式化字符串,字段之间的位置固定。一个例子更好地解释,这里有明显3个不同的字段,字符串是固定大小:
XXX 123 98.00
YYYYY 3 1.00
ZZ 42 123.34
How can I apply such formatting to a string in python (2.7)?
如何在python(2.7)中将这种格式应用于字符串?
1 个解决方案
#1
84
Sure, use the .format method. E.g.,
当然,使用.format方法。例如。,
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)
will print
将打印
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
您可以根据需要调整字段大小。请注意,.format独立于print工作以格式化字符串。我只是用print来显示字符串。简要说明:
10s
format a string with 10 spaces, left justified by default10s格式化一个包含10个空格的字符串,默认情况下左对齐
3d
format an integer reserving 3 spaces, right justified by default3d格式一个保留3个空格的整数,默认情况下右对齐
7.2f
format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.7.2f格式化一个浮点数,保留7个空格,小数点后2,右边默认为右。
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
还有许多其他选项来定位/格式化字符串(填充,左/右对齐等),字符串格式化操作将提供更多信息。
#1
84
Sure, use the .format method. E.g.,
当然,使用.format方法。例如。,
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)
will print
将打印
xxx 123 98.00
yyyy 3 1.00
zz 42 123.34
You can adjust the field sizes as desired. Note that .format
works independently of print
to format a string. I just used print to display the strings. Brief explanation:
您可以根据需要调整字段大小。请注意,.format独立于print工作以格式化字符串。我只是用print来显示字符串。简要说明:
10s
format a string with 10 spaces, left justified by default10s格式化一个包含10个空格的字符串,默认情况下左对齐
3d
format an integer reserving 3 spaces, right justified by default3d格式一个保留3个空格的整数,默认情况下右对齐
7.2f
format a float, reserving 7 spaces, 2 after the decimal point, right justfied by default.7.2f格式化一个浮点数,保留7个空格,小数点后2,右边默认为右。
There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.
还有许多其他选项来定位/格式化字符串(填充,左/右对齐等),字符串格式化操作将提供更多信息。