471,330 Members | 1,743 Online
Bytes | Software Development & Data Engineering Community
Post +

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 471,330 software developers and data experts.

The reverse of encode('...', 'backslashreplace')

Hi,

How can I transform b so that the assertion holds? I.e., how can I
reverse the backslash-replaced encoding, while retaining the str-type?
>>a = u''
b = a.encode('ascii', 'backslashreplace')
b
'\\xe6'
>>assert isinstance(b, str) and b == ''
Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
assert isinstance(b, str) and b == ''
AssertionError

Regards,
tores
Sep 4 '07 #1
1 4071
"Tor Erik Snvisen" <to*******@gmail.comwrote:
How can I transform b so that the assertion holds? I.e., how can I
reverse the backslash-replaced encoding, while retaining the str-type?
>>>a = u''
b = a.encode('ascii', 'backslashreplace')
b
'\\xe6'
>>>assert isinstance(b, str) and b == ''

Traceback (most recent call last):
File "<pyshell#59>", line 1, in <module>
assert isinstance(b, str) and b == ''
AssertionError
The simple answer is that you cannot: the backslashreplace isn't a
reversible operation. e.g. Try:
>>a = u'\\xe6'
print a
\xe6
>>b = a.encode('ascii', 'backslashreplace')
b
'\\xe6\\xe6'
>>>
There is no way after the encoding that you can tell which of the \xe6
sequences needs reversing and which doesn't. Perhaps the following is
what you want:
>>b = a.encode('unicode_escape')
print b
\\xe6\xe6
>>print b.decode('unicode_escape')
\xe6
>>>
Sep 4 '07 #2

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

7 posts views Thread by Robert | last post: by
2 posts views Thread by Edward Loper | last post: by
4 posts views Thread by thebjorn | last post: by
2 posts views Thread by geskerrett | last post: by
4 posts views Thread by Steven D'Aprano | last post: by
reply views Thread by rosydwin | last post: by

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.