473,402 Members | 2,053 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,402 software developers and data experts.

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

I use code like the following to retrieve fields from a form:

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

The intent is to finish by assigning the list to a string that I would
write to disk: recstr = string.join(recd,'')

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.
Is there a way to do this....so I can have spaces 'held' in the
object I want to write to the file ??
Thanks.
Jul 18 '05 #1
9 7978
John F Dutcher wrote in message
<2c**************************@posting.google.com>. ..
I use code like the following to retrieve fields from a form:

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

The intent is to finish by assigning the list to a string that I would
write to disk: recstr = string.join(recd,'')

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.
Is there a way to do this....so I can have spaces 'held' in the
object I want to write to the file ??
Thanks.


What does form.getfirst do? (Also, unless you're using an ancient Python,
the strings objects themselves have ljust methods and you don't need the
string module.)

string.ljust will never truncate or modify a string, only extend it, so I
don't know what you mean by having spaces "held". If the length of the
string is shorter than 15, string.ljust will return another string of length
15 with spaces on the right. But if its longer, string.ljust will return
the string unchanged (i.e., still longer than 15 chars).

Since you're writing this stuff to disk, I presume you need fixed-width
strings, so you can reliably read things back? If so, you can't safely use
string.ljust to pad *unless* you know *with certainty* that all strings fed
to it are 15 chars or shorter (because string.ljust won't truncate). So why
not use struct.pack and struct.unpack instead of string.join? (At least,
use string.joinwords() if you won't use ''.join())

E.g.:
recd = []
recd.append(form.getfirst("lname",' ')) # 'Avila' ?
recd.append(form.getfirst("fname",' ')) # 'Francis' ?

struct.pack('15s15s', *recd) # 'Avila\x00\x00Francis'
struct.unpack('15s15s', 'Avila\x00\x00Francis') # -> ('Avila', 'Francis')

Of course, struct pads with nulls, not spaces, so you already enter upon the
nasty world of binary files. You could postprocess the struct.pack string
with ''.replace('\x00', ' '), but you'll have to strip trailing spaces when
you struct.unpack().

You could write your own fixed-width-string class/function:

def fixedwidth(string, width=15):
if len(string) > width:
return string[:width]
else:
return string.ljust(width)

There's a lot of repetition going on here, so you might want to think of
wrapping all this functionality up in a 'formFieldSerializer' class of some
sort.

If it's possible to change the structure of what you write to disk, there
are a number of much better alternatives. Depending upon how rich your data
structure is and whether you need to name your fields, you could use (in
ascending complexity) colon-separated fields (':'.join(L). Remember to
escape colons in L!), the csv module, the ConfigParser module, or XML of
some kind (only if absolutely necessary). There are many other modules in
the std library which do serialization of some kind, like MimeWriter, etc.,
which may be appropriate for what you're doing. You can even use the db
modules if you need simple database.
--
Francis Avila

Jul 18 '05 #2
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>


Jul 18 '05 #3
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" <fr*****@pythonware.com> wrote in message news:<ma************************************@pytho n.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>

Jul 18 '05 #4
In the IDLE command shell this works exactly as expected, that is
ending spaces are preserved when joined to the 'rec' string:
(If I don't import and use 'string.ljust), and use just 'ljust' I get
a "Namerror'(Python 2.3.1)

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 for fields

"Francis Avila" <fr***********@yahoo.com> wrote in message news:<vr************@corp.supernews.com>...
John F Dutcher wrote in message
<2c**************************@posting.google.com>. ..
I use code like the following to retrieve fields from a form:

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

The intent is to finish by assigning the list to a string that I would
write to disk: recstr = string.join(recd,'')

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.
Is there a way to do this....so I can have spaces 'held' in the
object I want to write to the file ??
Thanks.


What does form.getfirst do? (Also, unless you're using an ancient Python,
the strings objects themselves have ljust methods and you don't need the
string module.)

string.ljust will never truncate or modify a string, only extend it, so I
don't know what you mean by having spaces "held". If the length of the
string is shorter than 15, string.ljust will return another string of length
15 with spaces on the right. But if its longer, string.ljust will return
the string unchanged (i.e., still longer than 15 chars).

Since you're writing this stuff to disk, I presume you need fixed-width
strings, so you can reliably read things back? If so, you can't safely use
string.ljust to pad *unless* you know *with certainty* that all strings fed
to it are 15 chars or shorter (because string.ljust won't truncate). So why
not use struct.pack and struct.unpack instead of string.join? (At least,
use string.joinwords() if you won't use ''.join())

E.g.:
recd = []
recd.append(form.getfirst("lname",' ')) # 'Avila' ?
recd.append(form.getfirst("fname",' ')) # 'Francis' ?

struct.pack('15s15s', *recd) # 'Avila\x00\x00Francis'
struct.unpack('15s15s', 'Avila\x00\x00Francis') # -> ('Avila', 'Francis')

Of course, struct pads with nulls, not spaces, so you already enter upon the
nasty world of binary files. You could postprocess the struct.pack string
with ''.replace('\x00', ' '), but you'll have to strip trailing spaces when
you struct.unpack().

You could write your own fixed-width-string class/function:

def fixedwidth(string, width=15):
if len(string) > width:
return string[:width]
else:
return string.ljust(width)

There's a lot of repetition going on here, so you might want to think of
wrapping all this functionality up in a 'formFieldSerializer' class of some
sort.

If it's possible to change the structure of what you write to disk, there
are a number of much better alternatives. Depending upon how rich your data
structure is and whether you need to name your fields, you could use (in
ascending complexity) colon-separated fields (':'.join(L). Remember to
escape colons in L!), the csv module, the ConfigParser module, or XML of
some kind (only if absolutely necessary). There are many other modules in
the std library which do serialization of some kind, like MimeWriter, etc.,
which may be appropriate for what you're doing. You can even use the db
modules if you need simple database.

Jul 18 '05 #5
Last shot ... then I'll leave you alone...I tried your 'fixedwidth'
function.
Almost predictably....it worked perfectly in IDLE when coded as below:
It has no effect at all when employed in the CGI script however, (the
returned
values do not have trailing spaces) ??

IDLE code:
def fixedwidth(string, width=15):
if len(string) > width:
return string[:width]
else:
return string.ljust(width)
ten = 'xxxxxxxxxx'
recd = []
recd.append(fixedwidth(ten))
recd.append(fixedwidth(ten))
recd.append(fixedwidth(ten))
rec = string.join(recd,'')
print rec
#f.close()
sys.exit()

Same code placed in CGI.... BUT....the passed string came in from the
form...can't see why there should be any difference.

"Francis Avila" <fr***********@yahoo.com> wrote in message news:<vr************@corp.supernews.com>...
John F Dutcher wrote in message
<2c**************************@posting.google.com>. ..
I use code like the following to retrieve fields from a form:

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

The intent is to finish by assigning the list to a string that I would
write to disk: recstr = string.join(recd,'')

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.
Is there a way to do this....so I can have spaces 'held' in the
object I want to write to the file ??
Thanks.


What does form.getfirst do? (Also, unless you're using an ancient Python,
the strings objects themselves have ljust methods and you don't need the
string module.)

string.ljust will never truncate or modify a string, only extend it, so I
don't know what you mean by having spaces "held". If the length of the
string is shorter than 15, string.ljust will return another string of length
15 with spaces on the right. But if its longer, string.ljust will return
the string unchanged (i.e., still longer than 15 chars).

Since you're writing this stuff to disk, I presume you need fixed-width
strings, so you can reliably read things back? If so, you can't safely use
string.ljust to pad *unless* you know *with certainty* that all strings fed
to it are 15 chars or shorter (because string.ljust won't truncate). So why
not use struct.pack and struct.unpack instead of string.join? (At least,
use string.joinwords() if you won't use ''.join())

E.g.:
recd = []
recd.append(form.getfirst("lname",' ')) # 'Avila' ?
recd.append(form.getfirst("fname",' ')) # 'Francis' ?

struct.pack('15s15s', *recd) # 'Avila\x00\x00Francis'
struct.unpack('15s15s', 'Avila\x00\x00Francis') # -> ('Avila', 'Francis')

Of course, struct pads with nulls, not spaces, so you already enter upon the
nasty world of binary files. You could postprocess the struct.pack string
with ''.replace('\x00', ' '), but you'll have to strip trailing spaces when
you struct.unpack().

You could write your own fixed-width-string class/function:

def fixedwidth(string, width=15):
if len(string) > width:
return string[:width]
else:
return string.ljust(width)

There's a lot of repetition going on here, so you might want to think of
wrapping all this functionality up in a 'formFieldSerializer' class of some
sort.

If it's possible to change the structure of what you write to disk, there
are a number of much better alternatives. Depending upon how rich your data
structure is and whether you need to name your fields, you could use (in
ascending complexity) colon-separated fields (':'.join(L). Remember to
escape colons in L!), the csv module, the ConfigParser module, or XML of
some kind (only if absolutely necessary). There are many other modules in
the std library which do serialization of some kind, like MimeWriter, etc.,
which may be appropriate for what you're doing. You can even use the db
modules if you need simple database.

Jul 18 '05 #6
John F Dutcher wrote:
Last shot ... then I'll leave you alone...I tried your 'fixedwidth'
function.
Almost predictably....it worked perfectly in IDLE when coded as below:
It has no effect at all when employed in the CGI script however, (the
returned
values do not have trailing spaces) ??


I am now pretty sure that fixedwidth() or str.ljust() are *not* the problem
with your cgi script. Step back and look for something *completely*
different, e. g.:
- Is it an old file that you are checking for the extra spaces?
- Do you think that print writes to a file (it can, if you do:
print >> destfile, "sometext")?

If you cannot track down the bug yourself, shorten the cgi script as much as
you can and post it on c.l.py. Try to describe the problem you perceive and
make as few implicit assumptions as possible, i. e. "This is my script's
output cut and pasted" rather than "It does not do what I want".

Peter
Jul 18 '05 #7

John F Dutcher wrote in message
<2c**************************@posting.google.com>. ..

I have nothing to add to help you with your problem (aside from what Peter
already said), but just a tip:

(If I don't import and use 'string.ljust), and use just 'ljust' I get
a "Namerror'(Python 2.3.1)

You probably learned Python out of an old book, back when Python didn't have
string methods. What I mean is, don't use the string module (it's slated
for depreciation), but just use ljust as a method of your string:
''.join(['a','b','c']) 'abc' 'a'.ljust(5) 'a ' '1234'.isdigit() True dir('')

['__add__', '__class__', '__contains__', '__delattr__', '__doc__', '__eq__',
'__ge__', '__getattribute__', '__getitem__', '__getnewargs__',
'__getslice__', '__gt__', '__hash__', '__init__', '__le__', '__len__',
'__lt__', '__mod__', '__mul__', '__ne__', '__new__', '__reduce__',
'__reduce_ex__', '__repr__', '__rmod__', '__rmul__', '__setattr__',
'__str__', 'capitalize', 'center', 'count', 'decode', 'encode', 'endswith',
'expandtabs', 'find', 'index', 'isalnum', 'isalpha', 'isdigit', 'islower',
'isspace', 'istitle', 'isupper', 'join', 'ljust', 'lower', 'lstrip',
'replace', 'rfind', 'rindex', 'rjust', 'rstrip', 'split', 'splitlines',
'startswith', 'strip', 'swapcase', 'title', 'translate', 'upper', 'zfill']

I'm sure you recognise many of those methods? To learn more, try help('')
in an interactive session.

--
Francis Avila
Jul 18 '05 #8
Peter Otten wrote:
I am now pretty sure that fixedwidth() or str.ljust() are *not* the problem
with your cgi script. Step back and look for something *completely*
different, e. g.:


Or maybe your browser holding an old response in its cache. Try holding
the shift key down while you click refresh.

Just a thought.

Steve

Jul 18 '05 #9
In article <2c*************************@posting.google.com> ,
Jo**********@urmc.rochester.edu (John F Dutcher) wrote:
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

Are you viewing your CGI program's output with an HTML browser?

Regards. Mel.
Jul 18 '05 #10

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

11
by: cjl | last post by:
Hey all: I want to convert strings (ex. '3', '32') to strings with left padded zeroes (ex. '003', '032'), so I tried this: string1 = '32' string2 = "%03s" % (string1) print string2 >32
3
by: chris ciotti | last post by:
Hello all - I'm trying to position content at the bottom of a page (I'd like to anchor it there). The majority of the code was generated using Photoshop CS and then hand edited. I'm having...
3
by: steve morin | last post by:
http://www.python.org/doc/2.4.1/lib/node110.html These methods are being deprecated. What are they being replaced with? Does anyone know? Steve
22
by: spike | last post by:
How do i reset a string? I just want to empty it som that it does not contain any characters Say it contains "hello world" at the time... I want it to contain "". Nothing that is.. Thanx
3
by: Sambo | last post by:
I have couple of puzzles in my code. def load_headers( group_info ): if os.path.isfile( group_info.pointer_file ): ptr_file = open( group_info.pointer_file, "r" ) else: print...
7
by: Leon | last post by:
Hi, I'm creating a python script that can take a string and print it to the screen as a simple multi-columned block of mono-spaced, unhyphenated text based on a specified character width and...
4
by: lurch132002 | last post by:
i am trying to create an array of structs to hold some information but whenever i get to the second element and try to strncpy it i get a segmenation fault. ive searched around for similar...
1
by: Shawn Minisall | last post by:
Hi everyone, I'm a beginning programming student in Python and have a few questions regarding strings. If s1 = "spam" If s2 = "ni!" 1. Would string.ljust(string.upper(s2),4) * 3 start it at...
2
by: davidson1 | last post by:
Hai friends..for menu to use in my website..i found in one website....pl look below website.... http://www.dynamicdrive.com/dynamicindex1/omnislide/index.htm i downloaded 2 files.... ...
0
by: Charles Arthur | last post by:
How do i turn on java script on a villaon, callus and itel keypad mobile phone
0
by: emmanuelkatto | last post by:
Hi All, I am Emmanuel katto from Uganda. I want to ask what challenges you've faced while migrating a website to cloud. Please let me know. Thanks! Emmanuel
1
by: nemocccc | last post by:
hello, everyone, I want to develop a software for my android phone for daily needs, any suggestions?
0
by: Hystou | last post by:
There are some requirements for setting up RAID: 1. The motherboard and BIOS support RAID configuration. 2. The motherboard has 2 or more available SATA protocol SSD/HDD slots (including MSATA, M.2...
0
marktang
by: marktang | last post by:
ONU (Optical Network Unit) is one of the key components for providing high-speed Internet services. Its primary function is to act as an endpoint device located at the user's premises. However,...
0
by: Hystou | last post by:
Most computers default to English, but sometimes we require a different language, especially when relocating. Forgot to request a specific language before your computer shipped? No problem! You can...
0
jinu1996
by: jinu1996 | last post by:
In today's digital age, having a compelling online presence is paramount for businesses aiming to thrive in a competitive landscape. At the heart of this digital strategy lies an intricately woven...
0
by: Hystou | last post by:
Overview: Windows 11 and 10 have less user interface control over operating system update behaviour than previous versions of Windows. In Windows 11 and 10, there is no way to turn off the Windows...
0
tracyyun
by: tracyyun | last post by:
Dear forum friends, With the development of smart home technology, a variety of wireless communication protocols have appeared on the market, such as Zigbee, Z-Wave, Wi-Fi, Bluetooth, etc. Each...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.