Page 1 of 1

Getting substring from string

Posted: Fri Aug 30, 2019 7:40 pm
by securigy
How can I extract the following substring
POS 2019/08/30 12:37:56 0 0E0C 1.20 2.21 -1.25 74 x0C

from string:
(b'dwm/position', b'POS 2019/08/30 12:37:56 0 0E0C 1.20 2.21 -1.25 74 x0C\r\n')

Re: Getting substring from string

Posted: Fri Aug 30, 2019 8:09 pm
by Roberthh
Do you have the while line after "from string:" as a single string item. I'm asking because as python element it is a tuple of two strings.
If yes, you can for instance use the expression:

s.split('\'')[3].strip() # Three single quotes in the brackets, one of the escaped.

assuming s is the variable holding you string. If it is a tuple, then you can access it with

s[1].strip()

strip() just removes the \r\n.

Re: Getting substring from string

Posted: Fri Aug 30, 2019 8:17 pm
by securigy
This is the original string I am interesting in:
b'POS 2019/08/30 12:37:56 0 0E0C 1.20 2.21 -1.25 74 x0C\r\n'

and I need to get rid of b' at the beginning and \r\n' and the end....
The code that I had worked before and now somehow does not...

The original string is not always of this format. Other formats that are result of a few initial headers can and should be ignored...

Re: Getting substring from string

Posted: Fri Aug 30, 2019 8:31 pm
by securigy
Hi Robert, I'd like to clarify the question...

I have the following messages coming:

b'Client PahoClient-on-RPi had unexpectedly disconnected'

followed by messages formatted like this:

b'POS 2019/08/30 12:45:11 0 0921 0.96 2.50 -0.93 72 x01\r\n'

messages that do not include POS should be ignored.

My original code was doing this:
idx = msg.find("POS")
if (idx >= 0):
substr = msg[idx:]
strToSend = re.sub('[\r\n\'\)]', '', strToSend)
print("Sending the packet to send: %s" % strToSend)
s.send(strToSend)

but now it breaks in the line idx = msg.find("POS") with error message:
TypeError: can't convert 'str' object to str implicitly

Any ideas? Or, how to avoid the problem if you recognize it (since I do not...)

Re: Getting substring from string

Posted: Sat Aug 31, 2019 12:10 am
by jimmo
The b' is actually not part of the contents of the string, it's telling you that this string is actually a byte array (i.e. it makes no assumptions about encoding, it's just a list of bytes).

You want to use .decode() to convert it to a regular string. You can use Python' 'in' operator to check for POS -- i.e. "if 'POS' in msg:"

Then to remove the whitespace from the end (i.e. \r\n) you can use .strip().