42 lines
1.2 KiB
Plaintext
42 lines
1.2 KiB
Plaintext
From: arcege at shore.net (Michael P. Reilly)
|
|
Date: Thu, 29 Apr 1999 18:58:07 GMT
|
|
Subject: padding strings
|
|
References: <roy-2904991402400001@qwerky.med.nyu.edu>
|
|
Message-ID: <3Z1W2.97$9L5.17946@news.shore.net>
|
|
X-UID: 220
|
|
|
|
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
|
|
|
|
|
|
|
|
|
|
|