How can I convert a string using re.compile

holger krekel pyth at devel.trillke.net
Wed May 15 11:13:23 EDT 2002


Christopher Myers wrote:
> Emile, I couldn't get your code to work for me, but I found it quite an
> engaging exercise to make something that did work.  Here's what I came
> up with:
> 
> def makeNewStr(str):
>     import string
>     var,list=string.split(str,"=")
>     var=string.strip(var)
>     list=string.strip(list)
>     list=list[1:-1]
>     list=string.split(list, ';')
>     newlist=[]
>     for trio in list:
>         numtrio=string.split(trio)
>         numlist="[ " + string.join(string.split(trio), ", ") + " ]"
>         newlist.append(numlist)
>     strlist="[ " + string.join(newlist, ", ") + " ]"
>     newstr= "%s = %s" %(var,strlist)
>     return newstr

hmmm. ok. here is a maintainable, flexible, stricter  version :-)

import re
def makeNewStr(line):
    # recognize syntax with sre's flexibility
    m = re.match(r'\s*(?P<name>\w+)\s*=\s*\[(?P<values>[^\]]+)\]',line)
    if not m: 
        raise SyntaxError,"in line: "+line

    # constructing the list of lists of string-floats
    # (raises ValueError for invalid strings)
    L = [ map(float,x.split()) and x.split() for x in m.group('values').split(';')]

    # explicit check for 3x3
    if len(L)!=3 or filter(lambda x: len(x)!=3, L):
        raise ValueError,"not 3x3 matrix: "+str(L)

    # returning the pythonic expression 
    return "%s=%s" % (m.group('name'),str(L).replace("'",""))


> I had originally tried something using typecasting to ints and floats,
> and then returning the repr() of the resulting list I created, but that
> ended up wiping out the scientific notation in those values, so then I
> decided to work completely using string manipulation, which was more
> concise anyway.

but then you loose the check if the strings are valid floats.

regards,

    holger





More information about the Python-list mailing list