How to print 0xfb in python

I'm falling in unicode hell.

My environment on unix, python 2.7.3

LC_CTYPE=zh_TW.UTF-8
LANG=en_US.UTF-8

I am trying to dump hex encoded data in a readable format, here is simplified code

#! /usr/bin/env python
# encoding:utf-8
import sys

s=u"readable\n"  # previous result keep in unicode string
s2="fb is not \xfb"  # data read from binary file
s += s2

print s   # method 1
print s.encode('utf-8')  # method 2
print s.encode('utf-8','ignore')  # method 3
print s.decode('iso8859-1')  # method 4

# method 1-4 display following error message
#UnicodeDecodeError: 'ascii' codec can't decode byte 0xfb 
# in position 0: ordinal not in range(128)

f = open('out.txt','wb')
f.write(s)

I just want to print 0xfb.

I should describe more here. Key + = s2 '. Where s will save my previous decrypted string. And s2 is the next line to be added to s.

If I changed as the following, this happens in the recording file.

s=u"readable\n"
s2="fb is not \xfb"
s += s2.decode('cp437')
print s
f=open('out.txt','wb')
f.write(s)
# UnicodeEncodeError: 'ascii' codec can't encode character
# u'\u221a' in position 1: ordinal not in range(128)

I want the result of out.txt to be

readable
fb is not \xfb

or

readable
fb is not 0xfb

[Decision]

#! /usr/bin/env python
# encoding:utf-8
import sys
import binascii

def fmtstr(s):
    r = ''
    for c in s:
        if ord(c) > 128:
            r = ''.join([r, "\\x"+binascii.hexlify(c)])
        else:
            r = ''.join([r, c])
    return r

s=u"readable"
s2="fb is not \xfb"
s += fmtstr(s2)
print s
f=open('out.txt','wb')
f.write(s)
+3
source share
1 answer

, : s += s2 one. s2 - , unicode ( ).

, "\ xfb" U+FB, LATIN SMALL LETTER U WITH CIRCUMFLEX, :

s2 = u"\u00fb"

, \xHH . , -, , , , repr . -, s , , .

s = s.encode('utf-8')
s += s2

print repr(s)

, , repr, - , Python ( ). - :

import re
controlchars_re = re.compile(r'[\x00-\x31\x7f-\xff]')

def _show_control_chars(match):
    txt = repr(match.group(0))
    return txt[1:-1]

def escape_special_characters(s):
    return controlchars_re.sub(_show_control_chars, s.replace('\\', '\\\\'))

controlchars_re, , .

+3

All Articles