Need better string methods

David MacQuigg dmq at gain.com
Mon Mar 8 14:15:39 EST 2004


Wow!! I am truly impressed with the quality of the discussion on this
topic, and the very excellent suggestions on how to best handle the
problems of complex operations on strings.  As nearly everyone has
pointed out, my original "best Python" 

clean = [' '.join(t.split()).strip('.') for t in line.split('|')]

is not right for the task at hand -- a two-day intro to Python for
EE's.  That one-liner was originally from my Ruby-Python comparison
page http://userlinux.com/cgi-bin/wiki.pl?RubyPython  It came out of a
discussion with people who are proficient in Python.

At this point I'm probably going to stick with a simple procedural
style, as suggested by Skip Montanaro and William Park

line = "..../bgref/stats.stf| SPICE | 3.2.7  | John    Anderson  \n"
# Line-by-line, with colorful names and comments.
pieces = line.split('|')   # split at the bars
# left-strip the dots
nodots  = [ piece.lstrip('.') for piece in pieces ]
def squeeze(words): return ' '.join(words.split())
clean = [squeeze(pieces) for pieces in nodots] # normalize spaces
print clean
['/bgref/stats.stf', 'SPICE', '3.2.7', 'John Anderson']

Still, I am tempted by the elegance and clarity of a sequence of
method calls.  I will have to resist that temptation, however, until
Python has some better built-in methods.  I know that even if I define
my own "StringOps" class, rather than stick to the basic tools in
Python, that will open the door to all sorts of "extensions" by people
whose job security depends on EE's not being able to do things for
themselves.  Not that we would forbid anyone to use the full power of
Python, but my hope is that we can put together a basic design tools
package where all of the scripts can serve as a pattern for an EE with
a two-day introduction to Python.

For those who would like to pursue this discussion of the best
programming styles, I put together a wiki page with a summary of what
I've learned so far.
http://userlinux.com/cgi-bin/wiki.pl?PythonStringOps 
Here is a sample:
4. Ideal syntax.  Start with a very complete set of string methods.
Add map and join list methods to allow operations on lists of strings.

                  / - -              - - \ 

string1.op1.split - - - .map.op2.op3 - - - .join.op4.op5

                  \ - -              - - /

Comments are welcome.

-- Dave




More information about the Python-list mailing list