[Tutor] Re: Question on Regular Expression Help

Don Arnold Don Arnold" <darnold02@sprynet.com
Sat Feb 8 09:32:02 2003


----- Original Message -----
From: "Alfred Milgrom" <fredm@smartypantsco.com>
To: <hsteiger@comcast.net>; <tutor@python.org>
Sent: Saturday, February 08, 2003 1:02 AM
Subject: [Tutor] Re: Question on Regular Expression Help


> >> I have spent some time without success, trying to read a line of data
> containing four numbers and storing each number into a variable. The line
> that is read is the following, which has been shortened some to remove
> extra spaces for this example. MX/MN 91 72 90 70 These numbers represent
> temperatures, and can vary, such as -11, -1, 0, 9 23, 75, 102, etc. So in
> order to use a regular expression to search for the numbers, I have to
> check for a dash (-) with up to 2 digits after the dash, and whether their
> could be up to 3 digits in each number. The problem is that my code cannot
> extract these numbers to store into the variables t1, t2, t3, and t4.
>
> Hi Henry:
>
> I don't think it is necessary to use "re", as simple string operations and
> list comprehension do the job easily.
>
> The following code illustrates the ideas:
>
> def isnumber(str):
>      digits = '-0123456789'
>      for letter in str:
> if letter not in digits:
>              return 0
>      return 1
>
> string = "MX/MN          91          72          90          70         "
> list = string.split(' ')
> list = [item for item in list if item and isnumber(item)]
> if len(list) == 4:
>      t1, t2, t3, t4 = list
>      print t1, t2, t3, t4
> else:
>      print "line does not contain four numbers'

You could also let Python decide for you whether or not a string can be
interpreted as an integer:

>>> def isInt(aString):
 try:
  int(aString)
  return True
 except:
  return False

>>> for substr in 'mx/mn    23 45  23.45 -456 3945'.split():
 print '%s : %d' % (substr, isInt(substr))

mx/mn : 0
23 : 1
45 : 1
23.45 : 0
-456 : 1
3945 : 1

HTH,
Don