[Tutor] Testing for punctuation in a string

Anna Ravenscroft anna at aleax.it
Sun Oct 12 17:35:34 EDT 2003


On Sunday 12 October 2003 06:52 pm, Alan Gauld wrote:
> > If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not sure

Make sure your list of fieldnames has quotes around each item, not just the 
beginning and end of the list... 

> what to do next.  I would probably split the string & test it a character
> at a time, but I am hoping for something better.  Thanks,

Ouch. Sounds long and unpleasant.

I like the nifty new sets module (available in 2.3). You can use a list 
comprehension (as Alan suggested) but if you have more than one type of "bad" 
punctuation in a particular fieldname, you'll get duplicates. If you use the 
new sets module, you can eliminate the duplicates. 

>>> import sets
>>> fieldnames=['fld1','fld2','fld-bad', 'fld-ba_d']
>>> bad = ['-'. '_']
>>> badfld = [f for f in fieldnames for b in bad if b in f]
>>> print badfld                            # will print any duplicates
['fld-bad', 'fld-ba_d', 'fld-ba_d']      
>>> setofbad = sets.Set(badfld)    # removes the duplicates
>>> print setofbad
Set(['fld-ba_d', 'fld-bad'])
>>>

Hope this gives you some ideas... Have fun.

Anna
-- 
There is a type 3 error in which your mind goes totally blank whenever you try 
to remember which is which of type 1 and type 2.
                                                 -Richard Dawkins




More information about the Tutor mailing list