gpt4 book ai didi

python - 根据字节数正确拆分 unicode 字符串

转载 作者:行者123 更新时间:2023-11-28 18:43:28 34 4
gpt4 key购买 nike

<分区>

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

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

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

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

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

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

34 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com