How can convert a string that looks like '\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82'
to something readable?
Asked
Active
Viewed 1.4k times
9

Karl Knechtel
- 62,466
- 11
- 102
- 153

synapse
- 5,588
- 6
- 35
- 65
-
Note that this is **not** a duplicate of https://stackoverflow.com/questions/4020539/; the input represents UTF-8 bytes which must be re-interpreted as UTF-8 *after* the backslash escape sequences have been unescaped. – Karl Knechtel Aug 04 '22 at 23:46
2 Answers
21
In python 2.7
>>> print '\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82'
привет
>>> print '\\xd0\\xbf\\xd1\\x80\\xd0\\xb8\\xd0\\xb2\\xd0\\xb5\\xd1\\x82'.decode('string-escape')
привет
>>> print r'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82'.decode('string-escape')
привет
In python 3.x
>>> br'\xd0\xbf\xd1\x80\xd0\xb8\xd0\xb2\xd0\xb5\xd1\x82'.decode('unicode-escape').encode('latin1').decode('utf-8')
'привет'

falsetru
- 357,413
- 63
- 732
- 636
-
2
-
i suggest that @synapse has r'\xd0\xb6\xd0\xbe\xd0\xbf\xd0\xb0', i.e. string with slashes. – eri Aug 08 '13 at 06:51
-
@eri, I used '\\' instead of raw string intentionally because this question is not python-only question. – falsetru Aug 08 '13 at 06:53
-
4
-
-
finally find the solutation!! Where do the python doc specify this situation. – selfboot Jun 09 '18 at 14:13
0
For file reading you may use this instead of open()
:
import codecs
with codecs.open('filename','r','string-escape') as f:
data=f.read()
data
will be reencoded while f
reading.

eri
- 3,133
- 1
- 23
- 35