[Novalug] Python Bug

donjr djr1952 at hotpop.com
Wed Jun 27 07:34:16 EDT 2007


On Tue, 2007-06-26 at 15:36 -0400, Ben Creitz wrote:
> On 6/26/07, Dan Arico <dan_arico at aricosystems.com> wrote:
> > I've run into a problem that has me puzzled. I was appending some data to
> > records in a flat text file. This is the section of code I was running
> > into the problem with:
> >
> >     while len(sen[0])<40:
> >         sen[0]=sen[0]+' '
> >     while len(sen[1])<40:
> >         sen[1]=sen[1]+' '
> >     rec=rec+sen[0]+sen[1]
> >
> > rec, sen[0] and sen[1] were read in as strings, but I had to pad sen[0]
> > and sen[1] with spaces so I'd get a constant size.
> >
> > What I discovered is the padding added spaces *after* the new line
> > character. When I appended everything together, I had two embedded line
> > feeds inside the records. Can someone explain why this happened and how
> > I should have done it?
> 
> 
> I think it is easiest to get rid of the newlines right when you read
> the strings in so that they don't get in the way later--I'm assuming
> they don't constitute actual data for you.  See examples of rstrip:
> 
>   # single-liners using rstrip()
>   strvar = strvar.rstrip()
>   filelines = [l.rstrip() for l in open(filename)]
> 
> Then you can use "\n".join(string_list) to rejoin them later if you need to.
> 
> Also, rather than using loops, you can do something like this:
> 
>   diff = 40 - len(str[0])
>   str[0] = str[0] + (" " * diff)
> 
> There might be an efficiency improvement to this approach because
> strings in Python are immutable, i.e. every time you append to one,
> Python is actually building a brand new one for you, which takes time.
> 
> ben

After remove the new line character 
Why not instead this to pad to 40 character minum:

  str[0] = '%-40s' % str[0]

After the above line 'str[0]' will be a minum of 40 characters long

Or for of 40 character long {and cutting off longer strings} try:

  str[0] = '%-40.40s' % str[0]

The above works under "Python 2.4.3" and is documented in the docs as
working.

--  
-- 
 Don E. Groves, Jr. 

$ /usr/games/fortune : 
The camel died quite suddenly on the second day, and Selena fretted
sullenly and, buffing her already impeccable nails -- not for the first
time since the journey begain -- pondered snidely if this would dissolve
into a vignette of minor inconveniences like all the other holidays
spent with Basil.
  -- Winning sentence, 1983 Bulwer-Lytton bad fiction contest. 



More information about the Novalug mailing list