是否有一种 Pythonic 方法可以按最大字节数截断 Unicode 字符串?

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)

Hom*_*512 5

这应该适用于 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 中,请确保指定编码。

  • 这可能应该明确命名编码。在大多数正常的平台上,它默认为 UTF-8,但有许多用户使用 Windows,因为他们不知道更好的方法,或者因为他们必须这样做。 (3认同)
  • @tripleee 在 Python 3 中,.encode() 和 .decode() 在 Windows 上也默认为“utf8”。 (3认同)