【问题标题】:How to replace r'\xb0' with r'\260'如何用 r'\260' 替换 r'\xb0'
【发布时间】:2013-11-09 19:01:02
【问题描述】:

如何在字符串中替换这些字符:r'\xb0' 与 r'\260',我已经尝试过:

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

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

【问题讨论】:

  • 你不想替换r'\xb0' 是吗?您要替换 字符,而不是 4 个字符的序列。 .replace('\xb0', r'\260') 会更合适。

标签: python unicode replace character


【解决方案1】:

你是说

>>> 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'

【讨论】:

  • 还有一个问题,如何避免双反斜杠 (\)?我只想得到一个;)
  • 你说的去掉反斜杠是什么意思? \\260C 只是一个字符串r'\260C' 的表示;字符串\260C\xb0C 等于:'\260C' == '\xb0C' 输出True
  • 我的问题是这里的结果:m/s\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\\ 262,因为我检查了“所有”可能的变体:例如text = text.encode('unicode-escape').replace(r'xb0', r'260') text = text.encode('unicode-escape').replace(r'\xb2', r'\262 ') 等等,每次调用都会添加新的反斜杠。我认为我的解决方案很糟糕。
  • 你可以在没有 unicode 转义的情况下完成。 .replace('\xb0', r'\260') 会做得很好。
  • @user2973395:什么,u'\xb0'.encode('latin1').replace('\xb0', r'\260') 对我来说很好用。你能给我们一个测试用例吗?具有预期输出的示例输入。
猜你喜欢
  • 2016-03-21
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2011-11-21
  • 2015-10-31
  • 2011-09-26
  • 2011-08-22
相关资源
最近更新 更多