PythonのID関数の使い方
inty98-admin
inty98
PythonでUUIDを生成する方法を記載します。
ランダムなIDを生成するにはpythonのuuidを使用します。
pythonで使用できるuuidには何種類かあるのですが、実行する度に値の変わるuuid4を使用します。(UUIDに関しては下記のページを見ていただけると幸いです。)
uuid4で生成した値をprintすると一見すると文字列になっていそうですが、実際にはUUIDクラスになっており、他の文字列と結合しようとしたりすると、エラーが発生します。そのため、str関数で文字列に変換する必要があります。
import uuid
id = uuid.uuid4()
# 出力結果: a762498a-acc1-44ab-a9a2-6d67361212b4
print(id)
# 出力結果: <class 'uuid.UUID'>
print(type(id))
# そのまま文字列との結合はできない
try:
id + "hoge"
except Exception as e:
# 出力結果: TypeError
print(e.__class__.__name__)
# 出力結果: unsupported operand type(s) for +: 'UUID' and 'str'
print(e)
# 文字列へ変換する
id_str = str(id)
# 出力結果: a762498a-acc1-44ab-a9a2-6d67361212b4
print(id_str)
# 出力結果: <class 'str'>
print(type(id_str))
UUIDクラスの.bytesから取得することができます。
import uuid
id = uuid.uuid4()
# 出力結果: <class 'bytes'>
print(type(id.bytes))
# 出力結果: b'\xa7bI\x8a\xac\xc1D\xab\xa9\xa2mg6\x12\x12\xb4'
print(id.bytes)
UUIDクラスの.intから取得することができます。
import uuid
id = uuid.uuid4()
# 出力結果: <class 'int'>
print(type(id.int))
# 出力結果: 222491411991069926082945803385771791028
print(id.int)
UUIDクラスの.hexから取得することができます。
import uuid
id = uuid.uuid4()
# 出力結果: <class 'str'>
print(type(id.hex))
# 出力結果: a762498aacc144aba9a26d67361212b4
print(id.hex)