9

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
  • 108,021
  • 142
  • 552
  • 849
Matt York
  • 15,641
  • 5
  • 45
  • 50
  • 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,641
  • 5
  • 45
  • 50
roippi
  • 24,635
  • 4
  • 45
  • 71
  • 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