4

Using Pythons string formatting, is there a nice way to add a suffix to a left aligned string that is padded to 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 the ':'. The best solution I found so far is to append the ':' to the key name:

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

But I think this is a rather ugly solution, as it diminishes the separation of formatting and values. Is it possible to achieve this directly in the format specification?

What I am looking for is something like this:

print "{do something here}  {}".format(key, value)
5
  • 1
    have you seen this stackoverflow.com/a/10837046/1984350?
    – Adeeb
    Feb 25, 2015 at 8:41
  • @Adeeb: That question does not cover the suffix I want to add
    – luator
    Feb 25, 2015 at 8:49
  • do you want the suffix to be immediately after the key text or do you want it to be after the remaining space if the key is smaller than the allocated space? which option between these paste.ubuntu.com/10404650
    – Adeeb
    Feb 25, 2015 at 8:55
  • @Adeeb: I want it immediately after the key (see my example), so the padding should be added after the suffix.
    – luator
    Feb 25, 2015 at 8:56
  • 1
    I think print "{:<20} {}".format(key+':', value) is fine.
    – martineau
    Feb 25, 2015 at 10:15

2 Answers 2

2

You cannot change "".format() as it is a built-in but if it is acceptable to provide the string and parameters to a method:

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

you can do so by subclassing string.Formatter to allow empty format fields and provide a special type handler 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))

gives you:

 a_key:               23
 another_key:         42

You can of course hardcode the ch, and w values:

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

for better readability, but less flexibility.


A backport of the Python 3.4 string.Formatter() that includes a bugfix for versions (at least) up to 3.5.0rc1, that includes this code is now available on PyPI

2
  • Much more complicated than I hoped, but it works, so thanks :).
    – luator
    Sep 8, 2015 at 14:03
  • Yes it would be much nicer if you could just patch that all on the built-in string and then call "....".altformat() but unfortunately you can't.
    – Anthon
    Sep 8, 2015 at 14:05
0

Here's one way:

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

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

Output:

another_key:           42
a_key:                 23

Another alternative would be:

    print '{}:{}{}'.format(key, ' '*(20-len(str(key))), value)
1
  • This is working, but it still has the flaw that formatting and data are mixed. I hoped there is some way to achieve this without having to add something in the .format(...) part.
    – luator
    Feb 25, 2015 at 16:19

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Not the answer you're looking for? Browse other questions tagged or ask your own question.