如何用r'\ 260'替换r'\ xb0'

时间:2013-11-09 19:01:02

标签: python unicode replace character

如何用字符串替换这些字符:r'\ xb0'和r'\ 260',我试过它:

test = u'\xb0C'
test = test.encode('latin1')
test = test.replace(r'\xb0', r'\260')

但它不起作用。问题是,我必须将数据写入八进制格式的文件(例如'\ 260C')而不是十六进制格式等。

1 个答案:

答案 0 :(得分:2)

你的意思是

>>> test.encode('unicode-escape').replace(r'\xb0', r'\260')
'\\260C'

>>> ''.join('\\%o' % ord(c) for c in test)
'\\260\\103'

或最慷慨的方法(事实证明OP实际上要求)

>>> table = {i: unicode(chr(i)) if 32 <= i < 128 else u'\\%o' % i for i in range(256)}
>>> u'\xb0ABD\260'.translate(table)
u'\\260ABD\\260'