[Tutor] Converting a String to a Tuple

Kent Johnson kent37 at tds.net
Sat Nov 5 00:52:14 CET 2005


Carroll, Barry wrote:
> Greetings:
> 
> My UDP client is receiving responses from the server, and now I need to
> process them.  A typical response string looks like this:
> 
>     "(0, ''),some data from the test system"
> 
> The tuple represents the error code and message.  If the command had failed,
> the response would look like this:
> 
>     "(-1, 'Error message from the test system')"
> 
> I need to extract the tuple from the rest of the response string.  I can do
> this using eval, like so: 
> 
>     errtuple = eval(mytxt[:mytxt.find(')')+1])
> 
> Is there another, more specific method for transforming a sting into a
> tuple?

This is pretty easy to do with a regular expression:
 >>> import re
 >>> tupleRe = re.compile(r"\((.*?), '(.*?)'\)")
 >>> tupleRe.search("(0, ''),some data from the test system").groups()
('0', '')
 >>> tupleRe.search("(-1, 'Error message from the test system')").groups()
('-1', 'Error message from the test system')

If you want the code as an integer instead of a string, you can extract the two values separately and convert the code:
 >>> code, msg = tupleRe.search("(-1, 'Error message from the test system')").groups()
 >>> code = int(code)
 >>> code
-1

To pick apart the regular expression:
r" # raw strings don't use the normal \ escapes, so the \ chars become part of the string
\( # look for a literal (
(.*?) # followed by anything, grouped
, '   # up to a literal comma space quote
(.*?) # followed by anything, grouped
'\)   # up to a literal quote )

The result of calling search is a match object; the group() method extracts the grouped sections of the re.

Kent
-- 
http://www.kentsjohnson.com



More information about the Tutor mailing list