unicode question

E

Edward Loper

I would like to convert an 8-bit string (i.e., a str) into unicode,
treating chars \x00-\x7f as ascii, and converting any chars \x80-xff
into a backslashed escape sequences. I.e., I want something like this:
u'abc \\xff\\xe8 def'

The best I could come up with was:

def decode_with_backslashreplace(s):
"str -> unicode"
return (s.decode('latin1')
.encode('ascii', 'backslashreplace')
.decode('ascii'))

Surely there's a better way than converting back and forth 3 times? Is
there a reason that the 'backslashreplace' error mode can't be used with
codecs.decode?
Traceback (most recent call last):
File "<stdin>", line 1, in ?
TypeError: don't know how to handle UnicodeDecodeError in error callback

-Edward
 
T

Tim Roberts

Edward Loper said:
I would like to convert an 8-bit string (i.e., a str) into unicode,
treating chars \x00-\x7f as ascii, and converting any chars \x80-xff
into a backslashed escape sequences. I.e., I want something like this:

u'abc \\xff\\xe8 def'

The best I could come up with was:

def decode_with_backslashreplace(s):
"str -> unicode"
return (s.decode('latin1')
.encode('ascii', 'backslashreplace')
.decode('ascii'))

Surely there's a better way than converting back and forth 3 times?

I didn't check whether this was faster, although I rather suspect it is
not:

cvt = lambda x: ord(x)<0x80 and x or '\\x'+hex(ord(x))
def decode_with_backslashreplace(s):
return ''.join(map(cvt,s))
 
K

Kent Johnson

Edward said:
I would like to convert an 8-bit string (i.e., a str) into unicode,
treating chars \x00-\x7f as ascii, and converting any chars \x80-xff
into a backslashed escape sequences. I.e., I want something like this:
u'abc \\xff\\xe8 def'

Kent
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,770
Messages
2,569,583
Members
45,074
Latest member
StanleyFra

Latest Threads

Top