I have a string that should be a UUID. Is there any built-in Python function available to check whether the UUID is valid or not, and to check its version?
I found this question while I was looking for a Python answer. To help people in the same situation, I've added the Python solution.
You can use the uuid
module:
#!/usr/bin/env python
from uuid import UUID
def is_valid_uuid(uuid_to_test, version=4):
"""
Check if uuid_to_test is a valid UUID.
Parameters
----------
uuid_to_test : str
version : {1, 2, 3, 4}
Returns
-------
`True` if uuid_to_test is a valid UUID, otherwise `False`.
Examples
--------
>>> is_valid_uuid('c9bf9e57-1685-4c89-bafb-ff5af830be8a')
True
>>> is_valid_uuid('c9bf9e58')
False
"""
try:
uuid_obj = UUID(uuid_to_test, version=version)
except ValueError:
return False
return str(uuid_obj) == uuid_to_test
if __name__ == '__main__':
import doctest
doctest.testmod()