如何在python中制作固定大小的格式化字符串? [英] How do I make a fixed size formatted string in python?

查看:50
本文介绍了如何在python中制作固定大小的格式化字符串?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

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

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:

XXX        123   98.00
YYYYY        3    1.00
ZZ          42  123.34

如何将这种格式应用于 python (2.7) 中的字符串?

How can I apply such formatting to a string in python (2.7)?

推荐答案

当然,使用 .format 方法.例如,

Sure, use the .format method. 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 工作以格式化字符串.我只是用 print 来显示字符串.简要说明:

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:

10s 用 10 个空格格式化字符串,默认左对齐

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

3d 格式化一个保留 3 个空格的整数,默认右对齐

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

7.2f 格式化一个浮点数,保留7个空格,小数点后2个,默认右对齐.

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

有许多附加选项来定位/格式化字符串(填充、左/右对齐等),字符串格式化操作 将提供更多信息.

There are many additional options to position/format strings (padding, left/right justify etc), String Formatting Operations will provide more information.

更新 f-string 模式.例如,

Update for f-string mode. E.g.,

text, number, other_number = 'xxx', 123, 98
print(f'{text:10} {number:3d}  {other_number:7.2f}')

右对齐

print(f'{text:>10} {number:3d}  {other_number:7.2f}')

这篇关于如何在python中制作固定大小的格式化字符串?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆