i come back to python; just some questions

Daniel Yoo dyoo at hkn.eecs.berkeley.edu
Mon Jul 15 01:47:10 EDT 2002


Fredrik Lundh <fredrik at pythonware.com> wrote:
: ppcdev wrote:
:> i was working on an old pentium II and wanted to send a very long
:> string in the USER parameter but it made my computer bug.. is it
:> normal???
:>
:> str='a'; r=range(1024);
:> for x in r[:]:
:>     str=str+str

The code here is saying "double the length of 'str' on every
iteration."  This is usually not a good thing to do.  *grin*


But if we want your string to be of length 1024, and we want to
construct the string with a loop, we'll can do the loop about lg(1024)
times:

###
>>> str = 'a'
>>> for i in range(10):
...     str = str + str
... 
>>> len(str)
1024
###

Notice here that we can avoid using variable names for values that we
use in Python.  That is, we don't need to say:

    r = range(10)

before using a range of length 10: we can plug that 'range(10)' in
"in-place" in our for loop statement, since that's probably the only
place that will use it.


But an alternative way of building that 'aaaa...' string, as the
others have mentioned, is to avoid using a loop and to use string
multiplication instead.  This is probably a better solution for your
problem.


Hope this helps!



More information about the Python-list mailing list