One-liner solution thanks to @CJ59:
# print random unicode character from the Basic Multilingual Plane (BMP)
import random
print(chr(random.randint(0,65536)))
From the Python 3 chr()
documentation:
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.
Solution that preserves the use of `chars` in my original question, thanks to @Matthias, allowing selection of hex digits for creating the unicode character:
# 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)))
Function that returns a random unicode character only if it is printable:
This function uses the str.isprintable()
method to only return a character if it is printable. This is useful if you want to generate a series of characters. Also includes an option for the character range.
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)
]
)
)