Mailing List Archive

padding strings
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?

--
Roy Smith <roy@popmail.med.nyu.edu>
New York University School of Medicine
padding strings [ In reply to ]
Roy Smith <roy@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
padding strings [ In reply to ]
Roy Smith 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?

How about this:

def mypad( s, num ):
return string.ljust( s, num )[:num]

--
Paul Prescod - ISOGEN Consulting Engineer speaking for only himself
http://itrc.uwaterloo.ca/~papresco

"Microsoft spokesman Ian Hatton admits that the Linux system would have
performed better had it been tuned."
"Future press releases on the issue will clearly state that the research
was sponsored by Microsoft."
http://www.itweb.co.za/sections/enterprise/1999/9904221410.asp
padding strings [ In reply to ]
padchar = ' '
N = 50

str = 'I need to be padded'
padded = (str+padchar*N)[:N]

print '>'+padded+'<'
print 'len:',len(padded)

--jim

-----Original Message-----
From: Roy Smith <roy@endeavor.med.nyu.edu>
Newsgroups: comp.lang.python
To: python-list@cwi.nl <python-list@cwi.nl>
Date: Thursday, April 29, 1999 2:01 PM
Subject: padding strings


>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?
>
>--
>Roy Smith <roy@popmail.med.nyu.edu>
>New York University School of Medicine
>