加入收藏 | 设为首页 | 会员中心 | 我要投稿 李大同 (https://www.lidatong.com.cn/)- 科技、建站、经验、云计算、5G、大数据,站长网!
当前位置: 首页 > 编程开发 > Python > 正文

python – 打印字符串左对齐,固定宽度和后缀

发布时间:2020-12-20 13:47:47 所属栏目:Python 来源:网络整理
导读:使用 Pythons字符串格式化,是否有一种很好的方法可以将后缀添加到左对齐的字符串中,该字符串填充为固定大小? 我想以下列格式打印键值对列表: a_key: 23another_key: 42... 问题是’:’.到目前为止我找到的最佳解决方案是将’:’附加到密钥名称: print "
使用 Pythons字符串格式化,是否有一种很好的方法可以将后缀添加到左对齐的字符串中,该字符串填充为固定大小?

我想以下列格式打印键值对列表:

a_key:        23
another_key:  42
...

问题是’:’.到目前为止我找到的最佳解决方案是将’:’附加到密钥名称:

print "{:<20}  {}".format(key+':',value)

但我认为这是一个相当丑陋的解决方案,因为它减少了格式和价值的分离.是否有可能直接在格式规范中实现这一点?

我正在寻找的是这样的:

print "{do something here}  {}".format(key,value)

解决方法

您不能更改“”.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,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,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{}<{}} {}',k,ch,w,v))

给你:

a_key:               23
 another_key:         42

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

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

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

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

(编辑:李大同)

【声明】本站内容均来自网络,其相关言论仅代表作者个人观点,不代表本站立场。若无意侵犯到您的权利,请及时与联系站长删除相关内容!

    推荐文章
      热点阅读