具有这样的utf-8编码字符串:
bar = "hello 。◕‿‿◕。"
还有一个字节偏移量,该偏移量告诉我必须拆分字符串的字节:
bytes_offset = 9
如何将条形字符串分成两部分,导致:
>>first_part
'hello 。' <---- #9 bytes 'hello \xef\xbd\xa1'
>>second_part
'◕‿‿◕。'
简而言之:
给定一个字节偏移量,如何将其转换为utf-8编码字符串的实际char索引位置?
最佳答案
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。