【问题标题】:Split an utf-8 encoded string given a bytes offset (python 2.7)拆分给定字节偏移量的 utf-8 编码字符串(python 2.7)
【发布时间】:2011-11-18 05:24:38
【问题描述】:

有一个像这样的 utf-8 编码字符串:

bar = "hello 。◕‿‿◕。"

还有一个字节偏移量,告诉我必须在哪个字节处拆分字符串:

bytes_offset = 9  

如何将条形字符串分成两部分导致:

>>first_part 
'hello 。' <---- #9 bytes 'hello \xef\xbd\xa1'
>>second_part 
'◕‿‿◕。'

简而言之
给定一个字节偏移量,如何将其转换为 utf-8 编码字符串的实际字符索引位置?

【问题讨论】:

    标签: python bytearray byte


    【解决方案1】:

    UTF-8 Python 2.x 字符串基本上是字节字符串。

    # -*- coding: utf-8 -*- 
    
    bar = "hello 。◕‿‿◕。"
    assert(isinstance(bar, str))
    
    first_part = bar[:9]
    second_part = bar[9:]
    print first_part
    print second_part
    

    产量:

    hello 。
    ◕‿‿◕。
    

    这里是 OSX 上的 Python 2.6,但我希望 2.7 也一样。如果我分成 10 或 11 而不是 9,我会得到 ?字符输出暗示它破坏了多字节字符序列中间的字节序列;在 12 上拆分将第一个“眼球”移动到字符串的第一部分。

    我在终端中将 PYTHONIOENCODING 设置为 utf8。

    【讨论】:

    • 我想你的意思是assert(isinstance(bar, str))assert(type(bar) is str)
    • 当然。出于某种原因,我永远记不起 isinstance() 的操作数顺序。
    【解决方案2】:

    字符偏移是字节偏移前的字符数:

    def byte_to_char_offset(b_string, b_offset, encoding='utf8'):
        return len(b_string[:b_offset].decode(encoding))
    

    【讨论】:

      猜你喜欢
      • 2022-01-09
      • 2015-07-01
      • 2017-02-04
      • 1970-01-01
      • 2011-10-06
      • 1970-01-01
      • 2011-08-16
      • 1970-01-01
      • 2011-11-16
      相关资源
      最近更新 更多