pythonicode:如何用空格替换不能用utf8解码的字符?

2024-09-30 12:22:18 发布

您现在位置:Python中文网/ 问答频道 /正文

如何用空格替换不能用utf8解码的字符?在

# -*- coding: utf-8 -*-
print unicode('\x97', errors='ignore') # print out nothing
print unicode('ABC\x97abc', errors='ignore') # print out ABCabc

如何打印出ABC abc而不是{}?注意,\x97只是一个示例字符。无法解码的字符是未知输入。在

  • 如果我们使用errors='ignore',它将不打印任何内容。在
  • 如果我们使用errors='replace',它将用一些特殊字符替换该字符。在

Tags: unicodeutf8out解码字符utfignore空格
2条回答

您可以使用try-except语句来处理UnicodeDecodeError

def my_encoder(my_string):
   for i in my_string:
      try :
         yield unicode(i)
      except UnicodeDecodeError:
         yield '\t' #or another whietespaces 

然后使用str.join方法连接字符串:

^{pr2}$

演示:

>>> print ''.join(my_encoder('this is a\x97n exam\x97ple'))
this is a   n exam  ple

看看codecs.register_error。可以使用它注册自定义错误处理程序

{a1}

import codecs
codecs.register_error('replace_with_space', lambda e: (u' ',e.start + 1))
print unicode('ABC\x97abc', encoding='utf-8', errors='replace_with_space')

相关问题 更多 >

    热门问题