[英]Print a random unicode character (without using exec)
我試圖弄清楚如何使用格式\\uXXXX
在 Python 3 中打印隨機 unicode 字符,其中每個X
是[0-F]
一個字符。 這是我到目前為止:
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
。 有沒有更 Pythonic 的方法來做到這一點?
編輯:從標題來看,這個問題似乎是#1477294“Generate random UTF-8 string in Python”的重復,但該問題在編輯中重新表述,因此那里的答案通常不會回答原始問題,他們也不回答這個問題。
# print random unicode character from the Basic Multilingual Plane (BMP)
import random
print(chr(random.randint(0,65536)))
來自 Python 3 chr()
文檔:
鉻(一)
返回表示其 Unicode 代碼點為整數 i 的字符的字符串。 例如,chr(97) 返回字符串 'a',而 chr(8364) 返回字符串 '€'。 這是 ord() 的倒數。
參數的有效范圍是從 0 到 1,114,111(以 16 為底的 0x10FFFF)。 如果 i 超出該范圍,則會引發 ValueError 。
# print unicode character using select hex chars
import random
chars = '0123456789ABCDEF'
# create random 4 character string from the characters in chars
hexvalue = ''.join(random.choice(chars) for _ in range(4))
# convert string representation of hex value to int,
# then convert to unicode character for printing
print(chr(int(hexvalue, 16)))
此函數使用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)
]
)
)
您可以創建一個永久循環,該循環將生成一個隨機的 unicode 字符及其 ID 和編號。 此外,它永遠不會崩潰。 (除非你做了一些瘋狂的事情。)刪除 'while True:' 以停止永遠循環並刪除 'sleep (1)' 以停止等待時間。
from random import randint
from time import sleep
while True:
try:
sleep(1)
a=(randint(1,65663))
print('Character:')
print(chr(a))
print('ID:' + str(hex(a)))
print('Number:' + str(a) + '\n\n\n\n\n\n\n\n\n\n\n\n\n')
except UnicodeEncodeError:
print('Character is not possible to print. Moving on.')
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.