[Tutor] Testing for punctuation in a string

Alan Gauld alan.gauld at blueyonder.co.uk
Sun Oct 12 12:52:36 EDT 2003


> If s is my list of fieldnames (s='fld1,fld2,fld-bad'), I'm not sure
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,

Ultimately you will have to test each character but you want to
do it in C rather than Python. However the best I can think of
is a comprehension:

class Oops(Exception): pass

def checkName(name):
  # use comprehension to maximise use of C code
  if len([char for char in name if char in punctuation]) == 0
      raise Oops

ok = []
for name in names:
   try:
      checkName(name)
      ok.append(name)
   except Oops:
      pass

HTH,

Alan G
Author of the Learn to Program web tutor
http://www.freenetpages.co.uk/hp/alan.gauld




More information about the Tutor mailing list