我希望将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
即使我处理了错误,也会在字符串末尾得到不需要的垃圾信息。
如何更优雅地解决这个问题?