[Python-au] String Casting

Daryl Tester Daryl.Tester at iocane.com.au
Fri Mar 25 01:37:08 CET 2005


Bryce Macdonald wrote:

> I have a string that is posted to my python program (which I cant control)
> that contains the literal r'\x7E\x0D\x0A' and I want it to convert it to
> equal '~\r\n'
> 
> Is there a way to convert this string ?

Definitely not elegant, and before my first cup o' coffee for the day has
sunk in, but how about something like:

>>> def convert(str):
...   newstr = ''
...   while str:
...     if str.startswith(r'\x'):
...       newstr += chr(string.atoi(str[2:4], 16))
...       str = str[4:]
...     else:
...       newstr += str[0]
...       str = str[1:]
...   return newstr
>>> convert(r'\x7e\x0d\x0a')
'~\r\n'

I don't think it would be efficient for long strings, but optimisation
is left as an exercise for the reader.  :-)


-- 
Regards,
  Daryl Tester,  Software Wrangler and Bit Herder, IOCANE Pty. Ltd.

"Security is like an onion; if I cut one up and jam it in your eye
 you'll know all about it." -- Conversations with Colleagues.




More information about the python-au mailing list