【问题标题】:Properly split unicode string on byte count [duplicate]根据字节数正确拆分 unicode 字符串 [重复]
【发布时间】:2014-05-01 17:43:20
【问题描述】:

我想将 unicode 字符串拆分为最多 255 个字节的字符并将结果作为 unicode 返回:

# s = arbitrary-length-unicode-string
s.encode('utf-8')[:255].decode('utf-8')

这个 sn-p 的问题是,如果第 255 字节字符是 2 字节 unicode 字符的一部分,我会得到错误:

UnicodeDecodeError: 'utf8' codec can't decode byte 0xd0 in position 254: unexpected end of data

即使我处理了错误,我也会在字符串末尾得到不需要的垃圾。

如何更优雅地解决这个问题?

【问题讨论】:

  • 我之前已经看到过这个确切的问题的回答;让我给你找个骗子。
  • 你是对的。在这里:stackoverflow.com/questions/6043463/…
  • @theta:好吧,那还是容易些。 :-P

标签: python unicode utf-8


【解决方案1】:

UTF-8 的一个非常好的特性是尾随字节可以很容易地与起始字节区分开来。只需向后工作,直到您删除了一个起始字节。

trunc_s = s.encode('utf-8')[:256]
if len(trunc_s) > 255:
    final = -1
    while ord(trunc_s[final]) & 0xc0 == 0x80:
        final -= 1
    trunc_s = trunc_s[:final]
trunc_s = trunc_s.decode('utf-8')

编辑:查看问题中被识别为重复的答案。

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2017-07-26
    • 2011-08-04
    • 2020-09-25
    • 2018-05-12
    • 2017-04-25
    • 2015-06-16
    • 1970-01-01
    • 2020-02-14
    相关资源
    最近更新 更多