Using 'string.ljust' to try and hold a fixed width.......

John F Dutcher John_Dutcher at urmc.rochester.edu
Wed Nov 19 19:41:02 CET 2003


There seems to be a difference between using IDLE to test the code and using
the same code in my CGI script as follows: (I'm using Python 2.3.1)


In the IDLE command shell this works exactly as expected, that is
ending spaces are preserved when joined to the 'rec' string:

ten = 'xxxxxxxxxx'    
recd = []
recd.append(string.ljust(ten,15))
recd.append(string.ljust(ten,15))
recd.append(string.ljust(ten,15))
rec = string.join(recd,'')
print rec     -----------------> ending spaces preserved
*************************************************************

In my CGI script where I retrieve 'form' data nothing works..
The use of a string to receive the form field first, and
then appending to 'recd'...or appending to 'recd' directly, both fail
to preserve the spaces....(which are preserved very well in the
IDLE mode using a string literal to start with, rather than 'form' data).

  	
recd = []
lname = string.ljust(form.getfirst("lname",' '),15)
fname = string.ljust(form.getfirst("fname",' '),15)

recd.append(lname)
recd.append(fname)

recstr = string.join(recd,'')
print recstr   ------------------> no ending spaces





"Fredrik Lundh" <fredrik at pythonware.com> wrote in message news:<mailman.884.1069251809.702.python-list at python.org>...
> John F Dutcher wrote:
> 
> > The spaces expected are 'NOT' being provided with 'string.ljust'....
> >
> > If I simply print the field immediately as in:
> >        print string.ljust(form.getfirst("lname",' '),15)
> >
> > they are not present; they are not present when assigned to the list,
> > and, of course, they are not present in the final string.
> 
> are you sure they're not there, or is the problem just that print
> doesn't show them to you?  try using "repr" or "len":
> 
> >>> import string
> >>> print repr(string.ljust("field", 15))
>  'field          '
> >>> print len(string.ljust("field", 15))
> 15
> 
> also note that ljust doesn't do anything if the input string is
> longer than the field width:
> 
> >>> print len(string.ljust("fieldfieldfieldfield", 15))
> 20
> 
> </F>




More information about the Python-list mailing list