打印随机unicode字符(不使用exec)

2024-09-27 07:21:00 发布

您现在位置:Python中文网/ 问答频道 /正文

我想知道如何使用\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"的复制品,但是这个问题在编辑中被重新措辞,因此那里的答案通常不会回答原始问题,也不会回答这个问题。在


Tags: informat编辑forstring格式unicoderandom
1条回答
网友
1楼 · 发布于 2024-09-27 07:21:00

@CJ59:

# print random unicode character from the Basic Multilingual Plane (BMP)
import random
print(chr(random.randint(0,65536)))

来自python3^{}文档:

chr(i)

Return the string representing a character whose Unicode code point is the integer i. For example, chr(97) returns the string 'a', while chr(8364) returns the string '€'. This is the inverse of ord().

The valid range for the argument is from 0 through 1,114,111 (0x10FFFF in base 16). ValueError will be raised if i is outside that range.

由于@Matthias允许选择十六进制数字来创建unicode字符:

^{pr2}$

函数,该函数仅在可打印时返回随机unicode字符:

此函数使用str.isprintable()方法仅返回可打印的字符。如果要生成一系列字符,这很有用。还包括字符范围的选项。在

import random
def randomPrintableUnicode(charRange = None):
    if charRange is None:
        charRange = (0,1114112)
    while True:
        i = random.randint(*charRange)
        c = chr(i)
        if c.isprintable():
            return c
        # should add another conditional break
        # to avoid infinite loop

# Print random unicode character
print(randomPrintableUnicode())

# Print random unicode character from the BMP
print(randomPrintableUnicode(charRange = (0,65536)))

# Print random string of 20 characters
# from the Cyrillic alphabet
cyrillicRange = (int('0410',16),int('0450',16))
print(
    ''.join(
        [
            randomPrintableUnicode(charRange = cyrillicRange)
            for _ in range(20)
        ]
    )
)

相关问题 更多 >

    热门问题