#1
  1. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2005
    Posts
    4
    Rep Power
    0

    String Processing Help


    Hello Everyone

    Here's the output string I'm working with:
    Code:
    xyz(0.583840, 3.141005, -0.001290) * trans(48.547394, 306.650513, -371.375366)
    I want to pick out the last three values and put them as numbers into an array like this:
    Code:
    [48.547393999999997, 306.65051299999999, -371.37536599999999]
    I have this working, but it's really slow and not flexible. For instance, it doesn't work well unless the string is exactly like the above. Here's my code:
    Code:
    def Process(tempvar):
    	temp=str(tempvar)
    	temp=temp.replace('(', '')
    	temp=temp.replace(')', '')
    	temp=temp.replace('trans','')
    	temp=temp.replace('*','')
    	temp=temp.replace('xyz','')
    	temp=temp.split('  ')
    	temp=temp[1].split(', ')
    	temp[0]=float(temp[0])
    	temp[1]=float(temp[1])
    	temp[2]=float(temp[2])
    	return temp
    As you can see, I'm manually taking bits and pieces out of the string, which is a dumb way to do it.

    What I'd like to do is search the string for the value 'trans' and then truncate the string to that point. Then I need to store the next three values as an array.

    Can anyone help with this?? Thanks in advance.
  2. #2
  3. No Profile Picture
    Contributing User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Nov 2004
    Posts
    394
    Rep Power
    51
    Hi!

    Maybe the easiest way is to use a regex:
    Code:
    import re
    
    s = "xyz(0.583840, 3.141005, -0.001290) * trans(48.547394, 306.650513, -371.375366)"
    
    regex = re.compile('trans\((.*?)\)')
    if regex.match:
        l = [float(x) for x in regex.findall(s)[0].split(',')]
    print l
    Hope this helps.

    Regards, mawe
  4. #3
  5. No Profile Picture
    Registered User
    Devshed Newbie (0 - 499 posts)

    Join Date
    Feb 2005
    Posts
    4
    Rep Power
    0
    Thanks mawe!

    That was exactly what I needed. It's faster and saved me a bunch of lines of code.
  6. #4
  7. Hello World :)
    Devshed Frequenter (2500 - 2999 posts)

    Join Date
    Mar 2003
    Location
    Hull, UK
    Posts
    2,537
    Rep Power
    69
    This can also be done without using regular expressions, and with even less code.

    Code:
    >>> aString = 'xyz(0.583840, 3.141005, -0.001290) * trans(48.547394, 306.650513, -371.375366)'
    >>> index = aString.rfind('(') + 1
    >>> [float(s) for s in aString[index:-1].split(', ')]
    [48.547393999999997, 306.65051299999999, -371.37536599999999]
    >>>
    Mark .
    programming language development: www.netytan.com Hula


IMN logo majestic logo threadwatch logo seochat tools logo