padding strings

Michael P. Reilly arcege at shore.net
Thu Apr 29 14:58:07 EDT 1999


Roy Smith <roy at popmail.med.nyu.edu> wrote:
: Given a string, I want to generate another string which is exactly N
: characters long.  If the first string is less than N, I want to blank-pad
: it.  If the first string is greater than N, I want to truncate it.

: What's the most straight-forward way to do that?

You can use format strings:
Python 1.5.1 (#3, Jul 16 1998, 10:35:48)  [GCC 2.7.2.2] on aix4
Copyright 1991-1995 Stichting Mathematisch Centrum, Amsterdam
>>> '%*s' % (10, "Michael")
'   Michael'
>>> '%-*s' % (10, "Michael")
'Michael   '
>>> '%-*.*s' % (10, 10, "Michael P. Reilly")
'Michael P.'
>>>

(Taken from section 2.1.5.1 "More String Operations" in the Python
Library Reference).

You can also use '%%' to delay some of the formatting:
  fmt = '%%-%d.%ds' % (10, 10)  # yields '%-10.10s'
  print repr(fmt % name)

This is probably more efficient if you are going to use the same
format widths repeatedly.

  -Arcege





More information about the Python-list mailing list