[Tutor] Re: Question on Regular Expression Help
Alfred Milgrom
fredm@smartypantsco.com
Sat Feb 8 02:06:01 2003
>> 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'
Hope this helps,
Fred Milgrom