String algo

Tim Chase python.list at tim.thechases.com
Sun Aug 9 18:47:26 CEST 2009


nipun batra wrote:
> I will be receiving data serially from another pc,.i can use any sort of
> marker between two packets,i will be the person sending data as well after
> reading it from some devices.But packet length is not constant.
> each packet has this format:
> 201.535a56.65b4.56c89.565d
> another packet could be :
> 4a5b6c7d
> What i need is a program to store variables such as:var_a has value 4,var_b
> has value 5,for second string.
> I have to read and write data continuosly using serial port.

Sounds like you want to break apart your string at the 
non-numeric bits, and then create a mapping from them:

 >>> import re
 >>> s = "201.535a56.65b4.56c89.565d"
 >>> r = re.compile(r"(\d+(?:\.\d+)?)([a-z]+)", re.I)
 >>> r.findall(s)
[('201.535', 'a'), ('56.65', 'b'), ('4.56', 'c'), ('89.565', 'd')]
 >>> d = dict((k,float(v)) for v,k in r.findall(s))
 >>> print d['a']
201.535
 >>> print d['c']
4.56
 >>> print 'z' in d
False
 >>> print 'b' in d
True

Adjust the regexp accordingly if there are +/- signs, 
exponentiation, limits on the splitting-characters, etc.


-tkc










More information about the Python-list mailing list