[Tutor] reading parts of a input string into different variables based on units.

Marc Tompkins marc.tompkins at gmail.com
Thu Mar 20 04:02:34 CET 2008


On Wed, Mar 19, 2008 at 3:56 PM, Tim Michelsen <timmichelsen at gmx-topmail.de>
wrote:

> m = 0
> cm = 0
> mm = 0
> ## first list item
> if first.endswith("m",-1):
>     m = first.strip("m")
> elif first.endswith("cm",-2):
>     cm = first.strip("cm")
> elif first.endswith("mm",-2):
>     mm = first.strip("mm")
> else:
>     print 'Wrong unit!'
> ## second list item
> if second.endswith("m",-1):
>     m = second.strip("m")
> elif second.endswith("cm",-2):
>     cm = second.strip("cm")
> elif second.endswith("mm",-2):
>     mm = second.strip("mm")
> else:
>     print 'Wrong unit!'
> ## third list item
> if second.endswith("m",-1):
>     m = second.strip("m")
> elif second.endswith("cm",-2):
>     cm = second.strip("cm")
> elif second.endswith("mm",-2):
>     mm = second.strip("mm")
> else:
>     print 'Wrong unit!'
>

Since they all end in "m", if you do that test first it catches all three
cases.  It's almost as if you put the "else" before the "if".
Regexes are a wonderful thing to learn - do that by all means - but the
simplest thing would be to reverse the order of your tests: check against
"mm" first, then "cm", THEN "m".

To clarify - regexes are probably the best solution for your current
program, but as a general rule it helps to look at tests like this from a
different angle.

-- 
www.fsrtechnologies.com
-------------- next part --------------
An HTML attachment was scrubbed...
URL: http://mail.python.org/pipermail/tutor/attachments/20080319/d969053d/attachment.htm 


More information about the Tutor mailing list