The print line on the left is aligned with a fixed width and suffix

Using Pythons line formatting, is there a good way to add a suffix to a left-aligned line that is padded with a fixed size?

I want to print a list of key-value pairs in the following formatting:

a_key:        23
another_key:  42
...

The problem is this :. The best solution I've found so far is to add ':' to the key name:

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

But I think this is a rather ugly solution, as it reduces the separation of formatting and values. Can this be achieved directly in the format specification?

What I'm looking for looks something like this:

print "{do something here}  {}".format(key, value)
+4
source share
2 answers

"".format(), , :

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

string.Formatter, t:

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{}<{}} {}', k, ch, w, v))

:

 a_key:               23
 another_key:         42

, , ch w:

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

, .


Python 3.4.Formatter(), ( ) 3.5.0rc1, , PyPI

+1

:

d = {'a_key': 23, 'another_key': 42}

for key, value in d.items():
    print '{}: {:<{width}} {}'.format(key, '', value, width=20-len(str(key)))

:

another_key:           42
a_key:                 23

:

    print '{}:{}{}'.format(key, ' '*(20-len(str(key))), value)
0

All Articles