The operating environment is Python3.6 Next ,Python2 There are many solutions online .
stay unicode In code , The scope of Chinese characters is (0x4E00, 9FBF)
import random
def Unicode():
val = random.randint(0x4e00, 0x9fbf)
return chr(val)
This method is relatively simple , But there's a small problem ,unicode Code contains 2 More than ten thousand Chinese characters , It contains many rare traditional characters .
gbk2312 Two bytes are used to encode characters , The range of the first byte is 0xB0-0xF7, The range of the second byte is 0xA1-0xFE.
Yes GBK2312 For a detailed explanation of the encoding method, please refer to GBK2312 code
''' No one answers the problems encountered in learning ? Xiaobian created a Python Exchange of learning QQ Group :857662006 Looking for small partners who share the same aspiration , Help each other , There are also good video tutorials and PDF e-book ! '''
import random
def GBK2312():
head = random.randint(0xb0, 0xf7)
body = random.randint(0xa1, 0xf9) # stay head Area code is 55 The last piece of 5 Chinese characters are garbled , In order to reduce the scope
val = f'{
head:x}{
body:x}'
str = bytes.fromhex(val).decode('gb2312')
return str
GBK2312 Included 6 More than a thousand commonly used Chinese characters . The choice between the two methods depends on the demand .