10

I have a unicode escaped string:

> str = 'blah\\x2Ddude'

I want to convert this string into the unicode unescaped version 'blah-dude'

How do I do this?

Martin Thoma
  • 124,992
  • 159
  • 614
  • 958
Matt York
  • 15,981
  • 7
  • 47
  • 51
  • It is not html escape string. Try: `import html; html.escape('this &escaped&')` and `html.unescape('this <is> &escaped&')` – jfs Mar 24 '14 at 09:28
  • Where does the string come from? Do you understand the difference between `'\\x2d'` and `'\x2d'`? – jfs Mar 24 '14 at 09:29

1 Answers1

15

Encode it to bytes (using whatever codec, utf-8 probably works) then decode it using unicode-escape:

s = 'blah\\x2Ddude'

s.encode().decode('unicode-escape')
Out[133]: 'blah-dude'
Matt York
  • 15,981
  • 7
  • 47
  • 51
roippi
  • 25,533
  • 4
  • 48
  • 73
  • 4
    It's not necessary to call the `encode` function. You can just `import codecs` and then call `codecs.decode(s, 'unicode-escape')` – Mark H Mar 18 '21 at 23:50