[Baypiggies] Discussion for newbies/beginner night talks (fwd)

Daniel Yoo dyoo at cs.wpi.edu
Sat Feb 10 06:00:39 CET 2007


I don't think my reply got through the first time (forgot that I'm using a 
different email address at WPI now.)  Let me refoward my message.

---------- Forwarded message ----------
Date: Fri, 9 Feb 2007 18:50:06 -0500 (EST)
From: Daniel Yoo <dyoo at cs.wpi.edu>
To: Dennis Reinhardt <DennisR at dair.com>
Cc: baypiggies at python.org
Subject: Re: [Baypiggies] Discussion for newbies/beginner night talks



> >  2) If you need to do a lot of string appends, use lists and join().
>
>  This is an optimization and as such may not be the first approach to
>  consider.  All of the code samples I showed used string appends such as
>
>         str  = ""
>          str += "string 1"
>          str +  "string 2"
>         ...

Hi Dennis,

I guess the other thing to point out is: if you're doing a lot of string 
appends, see if circumstances will let you can avoid it.  For example, if 
you're building xml output, don't do it by string appending things together if 
you can avoid it: build the xml tree, and have the xml library do the 
xml->string thing.


Related to this is making sure that if the problem involves data structures, 
use data structures: don't treat everything like a string. If we need to 
produce a dictionary whose keys are a combination of several values, don't 
string concatenate, but rather build a tuple, and use that as the key:

##########################################################
## not so good
def add_phone(book, first_name, last_name, phone_number):
      book[first_name + "," + last_name] = phone_number

def lookup(book, first_name, last_name):
      return book[first_name + "," + last_name]


## A little better
def add_phone(book, first_name, last_name, phone_number):
      book[(first_name, last_name)] = phone_number

def lookup(book, first_name, last_name):
     return book[(first_name, last_name)]
##########################################################


That is, sometimes we avoid string concatenation not because of efficiency, but 
because it's more correct to do so.  The first solution forces us to think 
about people putting in first_name and last_name combinations that concatenate 
to the same string, whereas the tuple solution has only one possible way of 
building that tuple.


Best of wishes!


More information about the Baypiggies mailing list