如何仅使用多字节字符生成 unicode 字符串

how to generate unicode strings only with multi-byte characters

如何生成一个 UTF-8 字符序列,其中每个字符由多个字节表示,并且每个字符都是从具有多字节表示的所有字符集中选择的?

我正在尝试测试我的应用程序如何处理带有多字节字符的 UTF-8。谢谢。

ASCII 范围 (U+0000 - U+007F) 之外的任何内容都会为您提供一个编码为多个 UTF-8 字节的 Unicode 字符。

只是随机生成那些:

import sys
import random

def random_nonascii_unicode(length):
    return u''.join(unichr(random.randint(0x80, sys.maxunicode)) for _ in range(length))

并根据需要编码为 UTF-8:

>>> random_nonascii_unicode(10)
u'\ue82a\u62ac\ufe97\u97a3\u02c5\u4955\u1ad8\u9cf7\u8cba\u62e7'
>>> random_nonascii_unicode(10).encode('utf8')
'\xe3\x98\xb8\xe6\x91\x84\xe9\x99\xab\xeb\xb3\x8d\xef\xb7\x91\xe9\x9e\x9f\xe9\x99\xb8\xee\x9a\x9d\xec\x86\x87\xed\xa1\xb0'