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

Tim Michelsen timmichelsen at gmx-topmail.de
Wed Mar 19 23:56:22 CET 2008


Hello,
I would like to read several parts of a string into different variables 
based on the (physical) units of the quantities.

Here's my testing code:
###############
mystring = '2m 4cm 3mm' # can also be '1pound 30pence', ...
mylist = mystring.split(" ")
print mylist

first = mylist[0]
second = mylist[1]
third = mylist[2]

print "first", first
print "second", second
print "third", third

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!'

print m, cm, mm
###############

Well, I cannot get the meters assigned to the m variable, the 
centimeters to the cm variable and the milimeters to the mm variable. 
All units end with "m" and therefore my code confuses the strings I am 
looking for. I would always reassign the m variable.

I would be very grateful of someone could give me a point or hint how I 
read the quantites (read: numbers) into my variables m, cm, mm.

Thanks and kind regards,
Timmie



More information about the Tutor mailing list