[Tutor] Converting a String to a Tuple
Orri Ganel
singingxduck at gmail.com
Fri Nov 4 23:57:35 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?
>
>Thanks as always.
>
>Barry
>
>
>_______________________________________________
>Tutor maillist - Tutor at python.org
>http://mail.python.org/mailman/listinfo/tutor
>
>
>
Well, if you want to avoid eval and are willing to deal with all the
elements being strings, you could use the following, though it could
probably be written prettier:
>>> tstr = "(-1, 'Error message from the test system')"
>>> tstrt = tuple( tstr[ tstr.find("("):tstr.find(")")+1 ].replace(
"(","" ).replace( ")","" ).split(", ") )
>>> tstrt
('-1', "'Error message from the test system'")
Basically, you first get the part of the string between the first set of
parentheses (so even if there are parentheses afterwards like "(0, '')
data (specifics of data)", it will still only get the "(0, '')" part),
then lose the parentheses, split the string along ", " and make the
string a tuple. Note that if you use this, you will either have to
guarantee that the string tuple elements will be separated by a comma
and a space, or change the above to "....split(","))", in which case
they will have to be separated by a comma (or you will have a space in
the element).
HTH,
Orri
P.S. - if you know that the first element will always be an integer and
that the second will always be a string, you can use the following for
better results:
>>> tstrt =
tuple((int(tstr[tstr.find("("):tstr.find(")")+1].replace("(","").replace(")","").split(",
")[0]),tstr[tstr.find("("):tstr.find(")")+1].replace("(","").replace(")","").split(",
")[1][1:-1]))
>>> tstrt
(-1, 'Error message from the test system')
For a while I tried to come up with some less lengthy lambdas to do the
job, but that would probably only serve to make it harder to read.
--
Email: singingxduck AT gmail DOT com
AIM: singingxduck
Programming Python for the fun of it.
More information about the Tutor
mailing list