bat*_*teo 2 python unicode python-3.x
如果 API 接受某些字节数限制的字符串值,但接受 Unicode,是否有更好的方法来缩短具有有效 Unicode 的字符串?
def truncate(string: str, length: int):
"""Shorten an Unicode string to a certain length of bytes."""
if len(string.encode()) <= length:
return string
chars = list(string)
while sum(len(char.encode()) for char in chars) > length:
chars.pop(-1)
return "".join(chars)
Run Code Online (Sandbox Code Playgroud)
这应该适用于 Python-3:
bytes_ = string.encode()
try:
return bytes_[:length].decode()
except UnicodeDecodeError as err:
return bytes_[:err.start].decode()
Run Code Online (Sandbox Code Playgroud)
基本上我们在第一个解码错误时截断。UTF-8 是前缀代码。因此,解码器应该始终能够看到字符串何时在字符中间被截断。口音之类的东西可能会出现奇怪的情况。我还没有想清楚这一点。也许我们也需要一些标准化。
在 Python-2 中,请确保指定编码。