Shaggy89
Shaggy89

Reputation: 709

Need to spilt string twice

As I'm still learning python I need some help.

Below is a sting that I need 2 separate lots of information out of. I've looked up how to get information out of strings but all examples ether put in a list or use numbers

msg= 'MFS: *CFSRES INC0020 01/12/14 07:51 RESPOND TEST ONLY, ALARM LEVEL: 1, 123 TESTSTREET TESTTOWN ,MAP: ,TG 100, == TESTING : UNIT HERE'

SO the information I want is 1 )RESPOND TEST ONLY, ALARM LEVEL: 1 2) =TESTING:

The sting will always change but the words RESPOND and the = will always be there.

The code I have tried:

msg='MFS: *CFSRES INC0020 01/12/14 07:51 RESPOND TEST ONLY, ALARM LEVEL: 1, 123 TESTSTREET TESTTOWN ,MAP: ,TG 100, == TESTING : UNIT HERE'
print msg.split(RESPOND)

output is

'MFS: *CFSRES INC0020 01/12/14 07:51 "," TEST ONLY, ALARM LEVEL: 1, 123 TESTSTREET TESTTOWN ,MAP: ,TG 100, == TESTING : UNIT HERE'

So I'm guessing that string.split() is not I what I would use or do need to use it in a different way?

Edit: using with pyttsx so getting main info out as string is so long

Upvotes: 0

Views: 78

Answers (1)

PeterE
PeterE

Reputation: 5855

As was commented before you should give us more information on what data you want to extract from the string.

Depending on how complex that is you should probably go with a regular expression instead. The Python HowTo is quite good as an introduction.

Your example could be solved as follows:

import re
pattern = re.compile('(?P<prefix>.*)RESPOND(?P<middle>.*?)=(?P<postfix>.*)')

msg = 'MFS: *CFSRES INC0020 01/12/14 07:51 RESPOND TEST ONLY, ALARM LEVEL: 1, 123 TESTSTREET TESTTOWN ,MAP: ,TG 100, == TESTING : UNIT HERE'

match = pattern.match(msg)

if match:
    print '[PREFIX]', match.group('prefix')
    print '[MIDDLE]', match.group('middle')
    print '[POSTFIX]', match.group('postfix')
else:
    print 'NO MATCH!!'

Output:

[PREFIX] MFS: *CFSRES INC0020 01/12/14 07:51 
[MIDDLE]  TEST ONLY, ALARM LEVEL: 1, 123 TESTSTREET TESTTOWN ,MAP: ,TG 100, 
[POSTFIX] = TESTING : UNIT HERE

Depending on what data you want you can modify the regular expression to almost anything.

EDIT:

I have adjusted the regexpr so that the result is what you want. You could do much more, e.g. extract the alarm level as a number, etc.

import re
pattern = re.compile('.*(RESPOND.*?ALARM\sLEVEL.*?),.*==\s(.*)\s:')

msg = 'MFS: *CFSRES INC0020 01/12/14 07:51 RESPOND TEST ONLY, ALARM LEVEL: 1, 123 TESTSTREET TESTTOWN ,MAP: ,TG 100, == TESTING : UNIT HERE'

match = pattern.match(msg)

if match:
  for group in match.groups():
      print group
else:
    print 'NO MATCH!!'

Output:

RESPOND TEST ONLY, ALARM LEVEL: 1
TESTING

Upvotes: 1

Related Questions