0

If I have a string containing four characters, for example:

'\\xf0'

How would I convert it to the escape sequence:

'\xf0'

I'm using Python 3.4.

Edit: I was trying to convert the string into the character which the string's value represents.

SuperNova
  • 138
  • 8
  • 1
    What exactly is in these strings? You must not realize it, but your question is not clear. You could clafiry by stating how many characters are in the original and the resulting string (the result of `len(string)`. – alexis Aug 27 '15 at 21:02
  • Your original string is a escaped string and your expected output is a hex value, So pls correct your question. – Mazdak Aug 27 '15 at 21:03
  • @alexis Sorry, I'm [obviously] new to this, is that proper now? – SuperNova Aug 27 '15 at 21:08
  • Also you can not replace \ with \\ because one backslash assumed as escape character by python so you need to replace the `\\x` with `\x`. – Mazdak Aug 27 '15 at 21:10
  • Your original string contains backslash, x, f, 0. Should the result be a single byte? (If so, it is _not_ an "escape sequence") – alexis Aug 27 '15 at 21:16

2 Answers2

2

What you're trying to do is interpret the escape sequences in the original string, to get the corresponding character(s). Don't compute them yourself, call a decode() method. In Python 3 you'll only find it on bytes objects (not str), so you need to convert to a bytes object and back:

>>> bytes("\\xf0\\xfa", "utf-8").decode("unicode_escape")
'ðú'

See here for a more complete answer to your question.

Community
  • 1
  • 1
alexis
  • 48,685
  • 16
  • 101
  • 161
0

I think this is what you want..

literal_version = '\\xf0'
byte_version = bytes([int('0'+literal_version[1:], 16)])
Chad S.
  • 6,252
  • 15
  • 25