[Tutor] ratios with regular expressions, split?

D-Man dsh8290@rit.edu
Thu, 12 Jul 2001 10:38:30 -0400


On Thu, Jul 12, 2001 at 04:11:00PM +0200, Remco Gerlich wrote:
| On  0, kevin parks <kp87@lycos.com> wrote:
| > Additionally the ratios might also be input as 7:6 or 7/6 and some have a
| > different number of digits, like 3/2, 81/80 and 127/128, etc. Also there is
| > no way to tell in advance if there will be a series of 3 ratios, 4 ratios,
| > or 53 ratios. What is the best way to do this? with regex or split? I bought
| > the Chun book and it has a regular expressions chapter that i am looking at
| > now, but i am not sure exactly the best way to get started on this.

| Anyway, I think that split would work fine. As long as you're certain the
| ratios always have a simple n/m format and are seperated by commas,
| something like
| 
| 
| l = "3/4, 4/5, 6/7"
| ratios = []
| for ratio in l.split(","):
|    n, m = ratio.split("/")
|    ratios.append(Ratio(n, m))

I think you want

    ratios.append(Ratio( int(n) , int(m) ))

instead, for the last line.  To be more robust you would also need a
try-except block around it to catch any ValueError exceptions, unless
you know for certain that the input is good (or you want the
ValueError to propagate up and terminate the interpreter).

-D