python - 如何在 python 中打印出 0xfb

标签 python

我正在坠入 unicode hell 。

我的环境在unix,python 2.7.3

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

我试图以人类可读的格式转储十六进制编码的数据,这里是简化的代码

#! /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)

我只想打印出 0xfb。

我应该在这里描述更多。关键是's += s2'。 s 将保留我之前解码的字符串。 s2 是下一个应该附加到 s 中的字符串。

如果我修改如下,它发生在写入文件时。

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)

我希望out.txt的结果是

readable
fb is not \xfb

readable
fb is not 0xfb

[解决方案]

#! /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)

最佳答案

我强烈怀疑您的代码实际上在前一行出错:s += s2 一行。 s2 只是一系列字节,不能任意附加到 unicode 对象(而是一系列代码点)。

如果您打算用 '\xfb' 来表示 U+FBLATIN SMALL LETTER U WITH CIRCUMFLEX,最好这样分配它:

s2 = u"\u00fb"

但是您说您只想打印出控制字符的\xHH 代码。如果你只是想让它成为人类可以理解的东西,这仍然使得字符串中的特殊字符很明显,那么 repr 可能就足够了。首先,不要让 s 成为 unicode 对象,因为您将此处的字符串视为一系列字节,而不是一系列代码点。

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

print repr(s)

最后,如果你不想在 repr 添加额外的引号,为了 pretty-print 或其他什么,没有一个简单的内置方法可以在 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 正则表达式来定义您关心转义的字符。

关于python - 如何在 python 中打印出 0xfb,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/10526761/

相关文章:

python - 如何判断 Sympy 变量是否为复数?

python - 数组中的圆形对?

python - 将列表列表导入列表数组中的文件

python - 使用 python 从大型 json 文件加载元素

python - 添加到人脸识别数据路径新图像,而不是覆盖它们

python - 将数字渲染到 n 个可变位置

python - 导入 nltk 时 Flask WSGI 应用程序挂起

python - 如何系统地重用 Dask 中延迟函数的结果?

python - 这个变量真的可以是 "referenced before assignment"

python - numpy中的随机单热矩阵