I want to split u"an arbitrary unicode string"
into chunks of say 300 bytes without destroying any characters. The strings will be written to a socket that expects utf8 using unicode_string.encode("utf8")
. I don't want to destroy any characters. How would I do this?
相关问题
- how to define constructor for Python's new Nam
- streaming md5sum of contents of a large remote tar
- How to get the background from multiple images by
- Evil ctypes hack in python
- Correctly parse PDF paragraphs with Python
If you can ensure that the utf-8 representation of your chars are only 2 byte long than you should be safe to split the unicode string into chunks of 150 chars (this should be true for most european encodings). But utf-8 is variable-width encoding. So might might split the unicode string into single characters, convert each char to utf-8 and fill your buffer until you reached the max chunk-size...this might be inefficient and a problem if high-throughput is an must...
UTF-8 has a special property that all continuation characters are
0x80
–0xBF
(start with bits 10). So just make sure you don't split right before one.Something along the lines of:
should do the trick.
Use unicode encoding which by design have fixed length of each character, for example
utf-32
:After encoding you can send chunk of any size (size must be multiple of 4 bytes) without destroying characters
Tested.
UTF-8 is designed for this.
Not tested. But you find a place to split, then backtrack until you reach the beginning of a character.
However, if a user might ever want to see an individual chunk, you may want to split on grapheme cluster boundaries instead. This is significantly more complicated, but not intractable. For example, in
"é"
, you might not want to split apart the"e"
and the"´"
. Or you might not care, as long as they get stuck together again in the end.