Re: [Tutor] rounding up to the nearest multiple of 8

2012-10-05 Thread Albert-Jan Roskam





> This is all fun, but what about the context?  Your original function
> took an integer, not a string, and thus wasn't charged with measuring
> string length, possibly multiple times.  Even so, each of these tests is
> taking around a microsecond.  So are you expecting to do anything with
> the result?  Just calling ljust() method more than doubled the time.  If
> you actually have some code to generate the string, and/or if you're
> going to take the result and write it to a file, then pretty soon this
> function is negligible time.
> 
> If it were my code, i think I'd use something like   "      
> "[-sz%8:] 
> and either prepend or append that to my string.  But if I had to do
> something more complex, I'd tune it to the way the string were being used.
> 

Yeah, maybe I got a little carried away. ;-) Knuth's 'premature optimization is 
the root of all evil' comes to mind. Then
again, it was fun from an educational point of view.

The context: the code is part of a program that writes spss system files 
(binary, .sav). These may be anything from 
a few hundred till millions of records. Spss knows to types of data: character 
and numerical. The code is only relevant
for char data. If a 5M record dataset has 8 char variables, it means 40M 
executions of the posted code snippet. Or around 40 seconds devoted to padding. 
But in general there are fewer values. I'll use cProfile later to see if there 
are more urgent pain spots. This seemed a good candidate as the function is 
used so often. FWIW, here is the function, plus some of the init:

def __init__(self, *args, *kwargs):
    self.strRange = range(1, MAXLENGTHS['SPSS_MAX_LONGSTRING'][0] + 1)
    self.pad_8_lookup = dict([(i, -8 * (i // -8)) for i in self.strRange])

    def writerow(self, record):
    """ This function writes one record, which is a Python list."""
    convertedRecord = []
    for value, varName in zip(record, self.varNames):
    charlen = self.varNamesTypes[varName]
    if charlen > 0:
    value = value.ljust( self.pad_8_lookup[charlen] )
    else:
    try:
    value = float(value)
    except ValueError:
    value = self.sysmis
    convertedRecord.append(value)
    caseOut = struct.pack(self.structFmt, *convertedRecord)
    retcode = self.spssio.spssWholeCaseOut(self.fh, caseOut)
    if retcodes.get(retcode) != "SPSS_OK":
    raise SPSSIOError("Problem writing row:\n" % " ".join(record), 
retcode)
    return retcode
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Install Program

2012-10-05 Thread Walter Prins
Hi,

On 5 October 2012 15:39, eddy van  wrote:
> Hi
>
> Were can i download the python install program for free

If you google "download python" you'll get lots of relevant hits.
That said, assuming you're using Windows, I recommend downloading one
of the ActiveState Python distributions from here:

http://www.activestate.com/activepython/downloads

If you're going to be following a book or tutorial, it's probably best
to match your the version of Python you downoad (e.g. 3.2 or 2.7) to
that used in the book.

Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Python Install Program

2012-10-05 Thread Jerry Hill
On Fri, Oct 5, 2012 at 10:39 AM, eddy van  wrote:
> Were can i download the python install program for free

Python installers are here: http://www.python.org/download/

You'll want either version 2.7.3 or 3.3.0, depending on whether you
need python 2 or python 3.  The actual installer you choose will
depend on the platform you're going to be running it on.  If you
happen to be on some flavor of linux, you're probably going to want to
use your platform's package manager instead.

-- 
Jerry
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Python Install Program

2012-10-05 Thread eddy van

Hi 

 

Were can i download the python install program for free

 

Thank you 

 
  ___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Through a glass, darkly: the datetime module

2012-10-05 Thread Albert-Jan Roskam


- Original Message -

> From: Richard D. Moores 
> To: Tutor List 
> Cc: 
> Sent: Friday, October 5, 2012 3:47 PM
> Subject: [Tutor] Through a glass, darkly: the datetime module
> 
> I thought it would be useful to have a script that would tell me what
> the date n days from today would be. The docs
> ()
> seem to get me almost there. I can compute the number of days between
> 2 dates, and the number of days between a date and today:
> 
> Python 3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)]
> 
> import time
> from datetime import date, timedelta
  date1 = date(2001, 9, 11)
  date1
> datetime.date(2001, 9, 11)
  date2 = date(2003, 4, 15)
  date2
> datetime.date(2003, 4, 15)
  date2 - date1
> datetime.timedelta(581)
  days_delta = date2 - date1
  days_delta.days
> 581
  today = date.today()
>  today
> datetime.date(2012, 10, 5)
  print(today)
> 2012-10-05
  time_to_date = today - date1
  time_to_date
> datetime.timedelta(4042)
  print(time_to_date)
> 4042 days, 0:00:00
  print(time_to_date.days)
> 4042
> 
> However, brick wall:
> 
> timedelta.days = 100
> Traceback (most recent call last):
>   File "", line 1, in 
> builtins.TypeError: can't set attributes of built-in/extension type
> 'datetime.timedelta'
> 
> Advice, please.

Hello,

Using Python 2.6:
import datetime
ndays = 10
print (datetime.datetime.today() + 
datetime.timedelta(days=ndays)).strftime("%Y-%m-%d") # prints  '2012-10-15'

Regards,
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Through a glass, darkly: the datetime module

2012-10-05 Thread Oscar Benjamin
On 5 October 2012 14:47, Richard D. Moores  wrote:
> I thought it would be useful to have a script that would tell me what
> the date n days from today would be. The docs
> ()
> seem to get me almost there. I can compute the number of days between
> 2 dates, and the number of days between a date and today:
>
> Python 3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)]
>
> import time
> from datetime import date, timedelta
 date1 = date(2001, 9, 11)
 date1
> datetime.date(2001, 9, 11)
 date2 = date(2003, 4, 15)
 date2
> datetime.date(2003, 4, 15)
 date2 - date1
> datetime.timedelta(581)
 days_delta = date2 - date1
 days_delta.days
> 581
 today = date.today()
> today
> datetime.date(2012, 10, 5)
 print(today)
> 2012-10-05
 time_to_date = today - date1
 time_to_date
> datetime.timedelta(4042)
 print(time_to_date)
> 4042 days, 0:00:00
 print(time_to_date.days)
> 4042
>
> However, brick wall:
>
> timedelta.days = 100
> Traceback (most recent call last):
>   File "", line 1, in 
> builtins.TypeError: can't set attributes of built-in/extension type
> 'datetime.timedelta'

timedlta objects are immutable. Once an object is created it's values
cannot be changed (much like a tuple). You need to create a new
timedelta object:

>>> from datetime import datetime, timedelta
>>> dt = datetime.now()
>>> print dt
2012-10-05 15:14:55.841000
>>> d = dt.date()
>>> print d
2012-10-05
>>> td = timedelta(days=7)
>>> print dt + td
2012-10-12 15:14:55.841000
>>> print d + td
2012-10-12

Oscar
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Through a glass, darkly: the datetime module

2012-10-05 Thread Walter Prins
Hi Richard

On 5 October 2012 14:47, Richard D. Moores  wrote:
> I thought it would be useful to have a script that would tell me what
> the date n days from today would be. The docs
> ()
> seem to get me almost there. I can compute the number of days between
> 2 dates, and the number of days between a date and today:

Does this hint help?

>>> import datetime
>>> mydate = datetime.date(2012,10,5)
>>> mydate = mydate + datetime.timedelta(days=30)
>>> print mydate
2012-11-04
>>>


Walter
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Through a glass, darkly: the datetime module

2012-10-05 Thread Mark Lawrence

On 05/10/2012 14:47, Richard D. Moores wrote:

I thought it would be useful to have a script that would tell me what
the date n days from today would be. The docs
()
seem to get me almost there. I can compute the number of days between
2 dates, and the number of days between a date and today:

Python 3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)]

import time
from datetime import date, timedelta

date1 = date(2001, 9, 11)
date1

datetime.date(2001, 9, 11)

date2 = date(2003, 4, 15)
date2

datetime.date(2003, 4, 15)

date2 - date1

datetime.timedelta(581)

days_delta = date2 - date1
days_delta.days

581

today = date.today()

today

datetime.date(2012, 10, 5)

print(today)

2012-10-05

time_to_date = today - date1
time_to_date

datetime.timedelta(4042)

print(time_to_date)

4042 days, 0:00:00

print(time_to_date.days)

4042

However, brick wall:

timedelta.days = 100
Traceback (most recent call last):
   File "", line 1, in 
builtins.TypeError: can't set attributes of built-in/extension type
'datetime.timedelta'

Advice, please.

Dick Moores
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor



From the docs http://docs.python.org/library/datetime.html class 
timedelta( [days[, seconds[, microseconds[, milliseconds[, minutes[, 
hours[, weeks]]])


hence timedelta(days=100)

--
Cheers.

Mark Lawrence.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] getattr works sometimes

2012-10-05 Thread Tino Dai
On Tue, Oct 2, 2012 at 8:39 PM, Steven D'Aprano  wrote:

> On 03/10/12 04:20, Tino Dai wrote:
>
>> and the get_class class works sometime for finding modules within a
 certain directory. If the get_class
 doesn't work, it throws an AttributeError.

>>>
>>> I don't really understand what you mean by this. Can you copy and
>>> paste the actual error message (all of it)?
>>>
>>>
 The module exists in the directory, and I'm trying to debug this. Does
 anybody have any hints to go about debug
 this?

>>>
>>>
>> get_class('etl.transfers.bill_**subject')  #
>> etl.transfers.bill_subject does exist under the transfers directory
>> > './leg_apps/etl/transfers/**bill_subject.pyc'>
>>
>
> I don't understand why you are using the get_class function for this.
> It is only useful when you don't know the name of the object until
> runtime. Since you know the name, I would suggest that using a regular
> import is better:
>
> from etl.transfers import bill_subject
>
> Imports also work differently to getattr, and I believe that is where
> you are running into trouble. The (wrongly named) get_class function
> uses getattr to extract names from a single top-level module. But that's
> not what you are trying to do: you are trying to extract modules from
> a package.
>

Where I was running into problems was the fact that I needed to import the
modules before I could do a getattr using the get_class function. In
retrospect, I'm bringing in basically all the objects anyway, so there
really is no need to have this complicated set up.

>
> Use the right tool for the job: you are trying to use a screwdriver when
> you need a screwdriver.
>
> My prediction is that *at some point* in your experiments, you have done
> something like:
>
> etl.transfers.bill_subject = bill_subject
>
> *or something with the same effect*. Perhaps the "transfers" module
> includes one of these lines:
>
> import bill_subject  # Python 2.5 or older?
> from . import bill_subject
>
>
> Now bill_subject is an attribute of the transfers module, and getattr can
> see it. But you haven't done the same for related_bills, and so getattr
> cannot see it.
>
> Instead, use the right tool, import, which is designed for solving your
> problem:
>
> from etl.transfers import bill_subject
> from etl.transfers import related_bills
>
> should both work, unless you have removed the bill_subject.py and
> related_bills.py files from the etl/transfers/ directory.
>
> Actually Steve, I don't know the correct classes to import until runtime.
This is part of a bigger ETL (Extract - Transform - Load) routine, and this
is the section that deals with records that didn't make it over because of
some missing constraint. You are probably right in the fact that I just
should import all the classes in and be done with it.

But that brings me to my next question, how do I prevent from polluting the
namespace with unneeded imports. Is there a way to de-import modules? Is
there an idiom that pertains to this?

Thanks,
Tino
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


[Tutor] Through a glass, darkly: the datetime module

2012-10-05 Thread Richard D. Moores
I thought it would be useful to have a script that would tell me what
the date n days from today would be. The docs
()
seem to get me almost there. I can compute the number of days between
2 dates, and the number of days between a date and today:

Python 3.2.3 (default, Apr 11 2012, 07:12:16) [MSC v.1500 64 bit (AMD64)]

import time
from datetime import date, timedelta
>>> date1 = date(2001, 9, 11)
>>> date1
datetime.date(2001, 9, 11)
>>> date2 = date(2003, 4, 15)
>>> date2
datetime.date(2003, 4, 15)
>>> date2 - date1
datetime.timedelta(581)
>>> days_delta = date2 - date1
>>> days_delta.days
581
>>> today = date.today()
 today
datetime.date(2012, 10, 5)
>>> print(today)
2012-10-05
>>> time_to_date = today - date1
>>> time_to_date
datetime.timedelta(4042)
>>> print(time_to_date)
4042 days, 0:00:00
>>> print(time_to_date.days)
4042

However, brick wall:

timedelta.days = 100
Traceback (most recent call last):
  File "", line 1, in 
builtins.TypeError: can't set attributes of built-in/extension type
'datetime.timedelta'

Advice, please.

Dick Moores
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rounding up to the nearest multiple of 8

2012-10-05 Thread Dave Angel
On 10/05/2012 07:23 AM, Albert-Jan Roskam wrote:
> - Original Message -
>
>> From: Asokan Pichai 
>> To: tutor@python.org
>> Cc: 
>> Sent: Friday, October 5, 2012 11:06 AM
>> Subject: Re: [Tutor] rounding up to the nearest multiple of 8
>>
>> If you are doing so many times, it may be worth precomputing the padding for 
>> a
>> given length and adding it by a look up on the length.
>>
>> For example:
>> 
>> SPACE = ' '
>> MAX = 1000
>> TAB = 8
>> paddding = [ SPACE * (n % TAB) for n in range(MAX) ]
>>
>> .
>> s = padding[len(s)] + s
>> .
>> --
>> where s is string to be padded
>>
>> Asokan Pichai
>
> Good idea! I know that the string values can never exceed 32767 bytes. So 
> when I combine all the advice I got here, the best way seems to be ver4, 
> using Eryksun's ver3 to initialize a dictionary:
>
> from timeit import timeit
> setup = "from math import ceil; value = 1040 * '*'"
> setup += "; " + "padLookup = dict([(i, -8 * (i // -8)) for i in range(1, 
> 32767+1)])"
> ver1 = timeit('int(ceil(len(value)/8.0)*8)', setup=setup)
> ver2 = timeit('len(value) + (-len(value) % 8)', setup=setup)
> ver3 = timeit('-8 * (len(value) // -8)', setup=setup)
> ver4 = timeit('padLookup[len(value)]', setup=setup)
>
> print ver1/ver4, ver2/ver4, ver3/ver4, ver4/ver4
>
> Thanks guys!
>

This is all fun, but what about the context?  Your original function
took an integer, not a string, and thus wasn't charged with measuring
string length, possibly multiple times.  Even so, each of these tests is
taking around a microsecond.  So are you expecting to do anything with
the result?  Just calling ljust() method more than doubled the time.  If
you actually have some code to generate the string, and/or if you're
going to take the result and write it to a file, then pretty soon this
function is negligible time.

If it were my code, i think I'd use something like   "   "[-sz%8:] 
and either prepend or append that to my string.  But if I had to do
something more complex, I'd tune it to the way the string were being used.


-- 

DaveA
 

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rounding up to the nearest multiple of 8

2012-10-05 Thread Albert-Jan Roskam
- Original Message -

> From: Asokan Pichai 
> To: tutor@python.org
> Cc: 
> Sent: Friday, October 5, 2012 11:06 AM
> Subject: Re: [Tutor] rounding up to the nearest multiple of 8
> 
> If you are doing so many times, it may be worth precomputing the padding for a
> given length and adding it by a look up on the length.
> 
> For example:
> 
> SPACE = ' '
> MAX = 1000
> TAB = 8
> paddding = [ SPACE * (n % TAB) for n in range(MAX) ]
> 
> .
> s = padding[len(s)] + s
> .
> --
> where s is string to be padded
> 
> Asokan Pichai


Good idea! I know that the string values can never exceed 32767 bytes. So when 
I combine all the advice I got here, the best way seems to be ver4, using 
Eryksun's ver3 to initialize a dictionary:

from timeit import timeit
setup = "from math import ceil; value = 1040 * '*'"
setup += "; " + "padLookup = dict([(i, -8 * (i // -8)) for i in range(1, 
32767+1)])"
ver1 = timeit('int(ceil(len(value)/8.0)*8)', setup=setup)
ver2 = timeit('len(value) + (-len(value) % 8)', setup=setup)
ver3 = timeit('-8 * (len(value) // -8)', setup=setup)
ver4 = timeit('padLookup[len(value)]', setup=setup)

print ver1/ver4, ver2/ver4, ver3/ver4, ver4/ver4

Thanks guys!
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie help with .pyc

2012-10-05 Thread Alan Gauld

On 05/10/12 10:07, Mark Lawrence wrote:

On 05/10/2012 04:23, ken brockman wrote:

I wonder if they might be a way for some on this forum to dispense
advice and help others without the totally snide and obnoxious
attitude?


I'm firmly with Steven here.  If people cannot be bothered to do any
research into how to ask they can expect snide responses.  If they don't
like that that they can move on,


There are valid points on both sides here.

We do need to remember that not all the people coming to tutor are 
experienced computer users, They are often youngsters just getting 
started in programming and as such have no experience of research or 
internet communities other than Facebook etc. Technical forums are very 
different and they need to be guided for their own benefit. At the other 
end we have older folks who might be very intelligent and experienced in 
research but not in computer fora or email lists.

These folks need to be educated in how to use technical forums but
in a reasonable way. Of course if they ignore the advice given then they 
should not expect the sympathetic manner to continue!


And then we have professionals moving from another language to python 
and here we would expect good questions, good formatting and the other 
things that show respect for their fellow professionals giving their 
time for free to help the community. Anything less is just laziness.


--
Alan G
Author of the Learn to Program web site
http://www.alan-g.me.uk/

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rounding up to the nearest multiple of 8

2012-10-05 Thread eryksun
On Fri, Oct 5, 2012 at 4:24 AM, Albert-Jan Roskam  wrote:
>
> import timeit
> ver1 = timeit.timeit("""
> import math
> value = "1234"
> value = "%-*s" % (int(math.ceil(len(value)/8.0)*8), value)
> """)
> ver2 = timeit.timeit("""
> value = "1234"
> value = value.ljust( len(value) + (-len(value) % 8) )
> """)

Try to focus a timeit run on the code that would actually run in a
loop. Move global imports, constants, and class/function definitions
into one or more setup strings.

>>> from timeit import timeit
>>> setup = "from math import ceil; value = '1234'"

>>> ver1 = timeit('int(ceil(len(value)/8.0)*8)', setup=setup)
>>> ver2 = timeit('len(value) + (-len(value) % 8)', setup=setup)
>>> ver3 = timeit('-8 * (len(value) // -8)', setup=setup)

>>> ver3 / ver2,  ver3 / ver1
(0.6623768153526971, 0.2884886334856229)
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] Newbie help with .pyc

2012-10-05 Thread Mark Lawrence

On 05/10/2012 04:23, ken brockman wrote:

I wonder if they might be a way for some on this forum to dispense advice and 
help others without the totally snide and obnoxious attitude? if it is so 
painfully annoying for you to deal with, why subject yourself to it? I suspect 
it is the sheer joy of showing others how bright you are and just how much 
disdain you have  for the lower forms of life you share the planet with.

Now give me a 4 paragraph long diatribe about top posting, netiquette and loads 
of all manner of minutia on the proper way to post and Make sure you do it in 
the most belittling way possible.





I'm firmly with Steven here.  If people cannot be bothered to do any 
research into how to ask they can expect snide responses.  If they don't 
like that that they can move on, as they're paying Steven the same 
amount that they're paying me, zilch.


--
Cheers.

Mark Lawrence.

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] I Need Help With Using Tkinter/Console/Creating GUIs

2012-10-05 Thread tayo rotimi
Thank you Steven; I am now running. I just followed your hint. I later noticed 
the author was actually referring to an earlier version of Python, with the 
console not looking the same with Python 3.2. 

Regards.

Tayo.___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rounding up to the nearest multiple of 8

2012-10-05 Thread Asokan Pichai
If you are doing so many times, it may be worth precomputing the padding for a
given length and adding it by a look up on the length.

For example:

SPACE = ' '
MAX = 1000
TAB = 8
paddding = [ SPACE * (n % TAB) for n in range(MAX) ]

.
s = padding[len(s)] + s
.
--
where s is string to be padded

Asokan Pichai

If a language is designed for non-programmers, soon only
non-programs get written in it.--- Anonymouse
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rounding up to the nearest multiple of 8

2012-10-05 Thread eryksun
On Fri, Oct 5, 2012 at 2:54 AM, Steven D'Aprano  wrote:
>
> py> from __future__ import division
> py> from math import ceil
> py> "%*s" % (int(ceil(len(mystring)/8)*8), mystring)
> '123412341234'
>
>
> Or left-justified:
>
> py> "%-*s" % (int(ceil(len(mystring)/8)*8), mystring)
> '123412341234'

Or use floor division with -n:

>>> lenstep = lambda s, n: -n * (len(s) // -n)

>>> mystring = '123412341234'
>>> "{1:<{0}s}".format(lenstep(mystring, 8), mystring)
'123412341234'
>>> "{1:>{0}s}".format(lenstep(mystring, 8), mystring)
'123412341234'
>>> "{1:^{0}s}".format(lenstep(mystring, 8), mystring)
'  123412341234  '
___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor


Re: [Tutor] rounding up to the nearest multiple of 8

2012-10-05 Thread Albert-Jan Roskam
- Original Message -

> From: Steven D'Aprano 
> To: tutor@python.org
> Cc: 
> Sent: Friday, October 5, 2012 8:54 AM
> Subject: Re: [Tutor] rounding up to the nearest multiple of 8
> 
> On Thu, Oct 04, 2012 at 05:26:13PM -0400, eryksun wrote:
>>  On Thu, Oct 4, 2012 at 4:04 PM, Joel Goldstick 
>  wrote:
>>  >
>>   my_string = "123"
>>   pad = 8 - len(my_string) % 8
>>   my_string = my_string + " " * pad
>>   my_string
>>  > '123     '
>> 
>>  If len(my_string) is already a multiple of 8, the above sets pad to 8:
>> 
>>      >>> s = "12345678"
>>      >>> pad = 8 - len(my_string) % 8
>>      >>> pad
>>      8
> 
> Here's another way:
> 
> 
> py> from __future__ import division
> py> from math import ceil
> py> "%*s" % (int(ceil(len(mystring)/8)*8), mystring)
> '    123412341234'
> 
> 
> Or left-justified:
> 
> py> "%-*s" % (int(ceil(len(mystring)/8)*8), mystring)
> '123412341234    '
> 
> 
> In Python 3, there is no need for the "from __future__" line.

Hi Steven, Eryksun, Joel,

Thanks for your replies! Steven, I noticed that the "from __future__" line can 
be omitted if len(mystring) is divided by 8.0 (ie, by a float rather than an 
int). I compared the "ceil" approach to the "modulo" approach, and found that 
the ceil approach is 2.6 times slower than the other approach. In this case, 
that's a relevant difference as the padding sometimes needs to be done millions 
of times.

import timeit
ver1 = timeit.timeit("""
import math
value = "1234"
value = "%-*s" % (int(math.ceil(len(value)/8.0)*8), value)
""")
ver2 = timeit.timeit("""
value = "1234"
value = value.ljust( len(value) + (-len(value) % 8) )
""")

print ver1
print ver2
print ver1 / ver2

___
Tutor maillist  -  Tutor@python.org
To unsubscribe or change subscription options:
http://mail.python.org/mailman/listinfo/tutor