1234567891011121314151617181920212223 |
- def truncate_by_concating(s, max_bytes):
- """
- Ensure that the UTF-8 encoding of a string has not more than
- max_bytes bytes
- :param s: The string
- :param max_bytes: Maximal number of bytes
- :return: The cut string
- """
- def len_as_bytes(s):
- return len(s.encode(errors='replace'))
- if len_as_bytes(s) <= max_bytes:
- return s
- res = ""
- for c in s:
- old = res
- res += c
- if len_as_bytes(res) > max_bytes:
- res = old
- break
- return res
|