truncate_1.py 530 B

1234567891011121314151617181920212223
  1. def truncate_by_concating(s, max_bytes):
  2. """
  3. Ensure that the UTF-8 encoding of a string has not more than
  4. max_bytes bytes
  5. :param s: The string
  6. :param max_bytes: Maximal number of bytes
  7. :return: The cut string
  8. """
  9. def len_as_bytes(s):
  10. return len(s.encode(errors='replace'))
  11. if len_as_bytes(s) <= max_bytes:
  12. return s
  13. res = ""
  14. for c in s:
  15. old = res
  16. res += c
  17. if len_as_bytes(res) > max_bytes:
  18. res = old
  19. break
  20. return res