Packing data

Jeff Shannon jeff at ccvcorp.com
Wed May 1 21:13:46 EDT 2002


In article <3CD0850E.94E6EC5F at uniserve.com>, bvdpoel at uniserve.com 
says...
> 
> I'm doing some midi stuff and need to pack ints into a byte string. I'm
> doing
> 
> def mkstring(var):
>  ret = ""
>  for a in var:
>   ret += chr(a)
>  return ret

Presuming that var is a list of ints, the following will be much 
more efficient than your code, without requiring array/struct.

def mkstring(var):
    var = [chr(a) for a in var]
    return ''.join(var)

The first line goes through your list of ints and converts it 
into a list of single characters.  The second line then joins 
that list into a single string, and returns it.  The biggest 
problem with your version is that, by using repeated string 
concatenation, you're creating a new, progressively longer and 
longer, temporary string item for each element of your list, in 
addition to the single-character string.  For lists of any 
significant length, this quickly becomes *very* inefficient.

-- 

Jeff Shannon
Technician/Programmer
Credit International



More information about the Python-list mailing list