在给定字节偏移量的情况下拆分utf-8编码的字符串(python 2.7)

问题描述 投票:1回答:2

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

bar = "hello 。◕‿‿◕。"

和一个字节偏移量告诉我在哪个字节我必须拆分字符串:

bytes_offset = 9  

如何将条形码分成两部分,从而产生:

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

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

python bytearray byte
2个回答
3
投票

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。


0
投票

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

def byte_to_char_offset(b_string, b_offset, encoding='utf8'):
    return len(b_string[:b_offset].decode(encoding))
© www.soinside.com 2019 - 2024. All rights reserved.