python格式输出占四列左对齐_python – 打印字符串左对齐,固定宽度和后缀

您不能更改“”.format(),因为它是内置的,但如果可以为方法提供字符串和参数:

print(kf.format("{:t{}} {}", key, ':', value))

您可以通过继承string.Formatter来允许空格式字段并提供特殊类型处理程序来实现:

from string import Formatter

import sys

if sys.version_info < (3,):

int_type = (int, long)

else:

int_type = (int)

class TrailingFormatter(Formatter):

def vformat(self, *args):

self._automatic = None

return super(TrailingFormatter, self).vformat(*args)

def get_value(self, key, args, kwargs):

if key == '':

if self._automatic is None:

self._automatic = 0

elif self._automatic == -1:

raise ValueError("cannot switch from manual field specification "

"to automatic field numbering")

key = self._automatic

self._automatic += 1

elif isinstance(key, int_type):

if self._automatic is None:

self._automatic = -1

elif self._automatic != -1:

raise ValueError("cannot switch from automatic field numbering "

"to manual field specification")

return super(TrailingFormatter, self).get_value(key, args, kwargs)

def format_field(self, value, spec):

if len(spec) > 1 and spec[0] == 't':

value = str(value) + spec[1] # append the extra character

spec = spec[2:]

return super(TrailingFormatter, self).format_field(value, spec)

kf = TrailingFormatter()

w = 20

ch = ':'

x = dict(a_key=23, another_key=42)

for k in sorted(x):

v = x[k]

print(kf.format('{:t{}

给你:

a_key: 23

another_key: 42

您当然可以对ch和w值进行硬编码:

print(kf.format('{:t:<20} {}', k, v))

为了更好的可读性,但灵活性较差.

Python 3.4 string.Formatter()的backport包含版本(至少)高达3.5.0rc1的错误修复,包含此代码现在可在PyPI上获得

  • 0
    点赞
  • 1
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值