How can I convert a string using re.compile

Christopher Myers chris.myers at ingenta.com
Wed May 15 09:46:21 EDT 2002


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

So, with s = 'a = [1   3.2 -3   ;   4e+3 5e-2  6e+10;  6.2  7 8e+1]'

I get:

>>> makeNewStr(s)
'a = [ [ 1, 3.2, -3 ], [ 4e+3, 5e-2, 6e+10 ], [ 6.2, 7, 8e+1 ] ]'


For a more concise return value, i.e. no spaces in the list, just
replace the ", " with "," in the joins and "[ " and " ]" with "[" and
"]" respectively in the string concatenations.

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.

However, while I was playing (yes, this was fun), I ended up writing a
function to return a string value of the scientific notation of any
string value passed in.  Check it out:

def makeSci(nstr):
    from math import fabs
    import string, re
    # Strip the decimal, and the exponent part if there
    str_no_dec = string.replace(nstr, ".", "")
    str_no_dec = re.split("E|e", str_no_dec)[0]
    # Here, I need to strip leading and trailing zeros
    while str_no_dec[0] == "0":
        str_no_dec=str_no_dec[1:]
    while str_no_dec[-1] == "0":
        str_no_dec=str_no_dec[:-1]
    # precision value to use in the format string
    precision = len(str_no_dec) - 1
    e=0
    try:
        b = float(nstr)
    except ValueError:
        return "Error"
    if fabs(b) < 1:
        while fabs(b) < 1:
            b=b*10
            e=e-1
    else:
        while fabs(b)>10:
            b=b/10
            e=e+1
    if e == 0:
        return nstr
    if e < 0: e = `e`
    else: e = "+"+`e`
    ret_precision = "%%.%dfe%%s" %precision
    return ret_precision %(b,e)


Please comment (ANYBODY!!) since I thought this was a pretty fun
puzzle-type exercise, and I'd love to see more like it.

-Chris

Emile van Sebille wrote:
> 
> "Emile van Sebille" <emile at fenx.com> wrote in message
> news:KwYD8.894$Bw6.280 at rwcrnsc51.ops.asp.att.net...
> > young-il sohn
> > > How can I convert the string 'a = [1 2 3;4 5 6;6 7 8]'
> > > to other string 'a = [[1,2,3],[4,5,6],[7,8,9]]' ?
> > >
> > > Numeric values can have various forms such as 3.2, -4, 3e+3, 3e-2,
> > > 3E+10, 3E-2 and so on. Space can be inserted in the list.
> >
> 
> Hmm, looks like I didn't quite meet the spec  ;-)
> 
> s = 'a = [1   3.2 -3   ;   4e+3 5e-2  6e+10;  6.2  7 8e+1]'
> 
> def nummify(val):
>     if val.startswith('['): val =val[1:]
>     if val.endswith(']'): val = val[:-1]
>     try:
>         float(val)
>         return repr(str(val))[1:-1]
>     except:
>         raise ValueError
> 
> print `s.split('=')[0]+" = "+`[[nummify(jj) for jj in ii.split()] for ii
> in s.split('=')[-1].split(";")]`.replace("'","")`
> 
> This works better.
> 
> --
> 
> Emile van Sebille
> emile at fenx.com
> 
> ---------

-- 
Christopher Myers, Graduate Software Developer 
Ingenta, Inc.
12 Bassett St.
Providence, RI  02903
ph:  401.331.2014 x 102
em:  chris.myers at ingenta.com
aim: chrismyers001



More information about the Python-list mailing list