[Tutor] where to insert?

Michael Janssen mi.janssen at gmail.com
Fri Sep 23 11:21:31 CEST 2005


On 9/22/05, Goofball223 at wmconnect.com <Goofball223 at wmconnect.com> wrote:

> I would like to insert string.join(msgList,"") into the following program where do I insert it?

do you want to build a temporary list and join its elements
afterwards? This can look like:

     # Loop through each substring and build ASCII message
     msgList = []
     for numStr in string.split(inString):
         asciiNum = int(numStr)           # convert digits to a number
         msgList.append(chr(asciiNum))
     # after completing the msgList, join it
     message = "".join(msgList)

Few notes: I have changed eval(numStr) into int(numStr) because int()
does everything you need here. eval() can do more but than just
converting digits into integers but this came at the cost of possible
unpredictable results. For example eval('1.23') is perfectly valid but
allowing floating point numbers wasn't your intention. int('1.23')
will fail with an exception wich is a good thing, because you can
catch the error and report the user back how to make better usage of
your programm. Other examples for unpredictable results with eval
invole eval('os.system("evilcommand")') or eval('range(2147483647)').
The latter would build a very large temporay list with numbers from 0
through 2147483646 which is likly to consume all of your machines
memory!

Second I'm using the "".join(msgList) (join as a string method)
instead of string.join(msgList, "") (join as a function of the string
modul), because it's slightly more readable and you mustn't remember
how string.join want to get its arguments.

Last not least: joining a list of strings instead of adding those
strings directly is a pattern used to avoid the problem that each
'alteration' of a string (as in 'message = message + chr(asciiNum)) is
in fact no alteration of the string but creates a new string every
time (because strings are immutable, i.e. can't be altered in place).
OTOH this problem doesn't seem to be such a big one ... In fact for
small strings and a small numer of them, the joining-a-list approach
can take more time. This is why I prefer to add strings directly and
only switch to an temporary list when I have really many strings or
when I gain some other advantages, when I e.g. want to join the
strings with a newline.


regards
Michael


More information about the Tutor mailing list