1. 程式人生 > 其它 >python 生成隨機16進位制數字(自定義規則)

python 生成隨機16進位制數字(自定義規則)

技術標籤:自用pythonpythonrandom

#自用的規則,如有需要自己改
#length表示希望生成的16進位制數長度
#範圍是0~16^length
#生成字母全部替換為大寫
#不夠位數的補0
def random_hex(length):
    result = hex(random.randint(0,16**length)).replace('0x','').upper()
    if(len(result)<length):
        result = '0'*(length-len(result))+result
    return result