我想知道如何使用\uXXXX
格式打印python3中的随机unicode字符,其中每个X
都是{
import random
chars = '0123456789ABCDEF'
L = len(chars)
fourRandInts = [random.randint(0,L-1) for i in range(4)]
fourRandChars = [chars[i] for i in fourRandInts]
s = r'\u{}{}{}{}'.format(*fourRandChars)
string = "print(u'{}')".format(s)
exec(string)
它似乎有效,但我宁愿避免使用exec
。有没有一种更像Python的方法?在
编辑:从标题来看,这个问题似乎是#1477294 "Generate random UTF-8 string in Python"的复制品,但是这个问题在编辑中被重新措辞,因此那里的答案通常不会回答原始问题,也不会回答这个问题。在
@CJ59:
来自python3^{} 文档:
由于@Matthias允许选择十六进制数字来创建unicode字符:
^{pr2}$函数,该函数仅在可打印时返回随机unicode字符:
此函数使用
str.isprintable()
方法仅返回可打印的字符。如果要生成一系列字符,这很有用。还包括字符范围的选项。在相关问题 更多 >
编程相关推荐