How to Check if a String is a Valid UUID in Python?

In this tutorial, I will explain how to check if a string is a valid UUID in Python. As a developer working on a project for a US-based company, I recently encountered a scenario where I needed to validate if a given string was a valid UUID. In this article, I will share my findings and provide examples to help you understand the process.

What are UUIDs (Universally Unique Identifier)

A UUID is a 128-bit identifier that is commonly used to uniquely identify objects or entities in a system. It is represented as a string of 32 hexadecimal digits, displayed in five groups separated by hyphens, in the form 8-4-4-4-12 of a total of 36 characters. Here’s an example of a valid UUID:

f65c57f6-a6aa-17a8-faa1-a67f2dc9fa91

Read How to Split a String into Equal Parts in Python?

Check UUID Validity in Python

Python provides a built-in module called uuid that allows us to work with UUIDs easily. The uuid module has a UUID class that can be used to validate and manipulate UUIDs. Let’s dive into the details.

1. Use the UUID Class

The most simple way to check if a string is a valid UUID is by using the UUID class from the uuid module. Here’s an example:

from uuid import UUID

def is_valid_uuid(uuid_string):
    try:
        UUID(uuid_string)
        return True
    except ValueError:
        return False

# Example usage
uuid_string1 = "f65c57f6-a6aa-17a8-faa1-a67f2dc9fa91"
uuid_string2 = "not-a-valid-uuid"

print(is_valid_uuid(uuid_string1))  
print(is_valid_uuid(uuid_string2)) 

Output:

True
False

I have executed the above code and added the screenshot below.

Check if a String is a Valid UUID in Python

In the code above, we define a function is_valid_uuid that takes a string uuid_string as input. Inside the function, we use a try-except block to attempt to create a UUID object from the given string. If the string is a valid UUID, the UUID object will be created successfully, and the function will return True. If the string is not a valid UUID, a ValueError will be raised, and the function will return False.

Read How to Insert a Python Variable into a String?

2. Check UUID Version

In some cases, you may need to check not only if a string is a valid UUID but also if it belongs to a specific version of UUID. UUID version 4 (random UUID) is the most commonly used. Here’s how you can check if a string is a valid UUIDv4:

from uuid import UUID

def is_valid_uuid_v4(uuid_string):
    try:
        # Parse the UUID
        uuid_obj = UUID(uuid_string)
        # Ensure it's version 4
        return uuid_obj.version == 4
    except ValueError:
        # If parsing fails, it's not a valid UUID
        return False

# Example usage
uuid_string1 = "f65c57f6-a6aa-17a8-faa1-a67f2dc9fa91"  
uuid_string2 = "00000000-0000-1000-8000-000000000000" 

print(is_valid_uuid_v4(uuid_string1))  
print(is_valid_uuid_v4(uuid_string2))  

Output:

False
False

I have executed the above code and added the screenshot below.

How to Check if a String is a Valid UUID in Python

In this example, we modify the is_valid_uuid function to is_valid_uuid_v4 and pass the version=4 parameter to the UUID constructor. This ensures that the string is not only a valid UUID but also a version 4 UUID.

Read How to Split a String by Index in Python?

Handle UUID Objects and Strings

When working with UUIDs in Python, you may encounter situations where you need to convert between UUID objects and their string representations. Here are a few examples:

1. Convert UUID to String

To convert a UUID object to its string representation, you can simply use the str() function:

from uuid import UUID

uuid_obj = UUID('f65c57f6-a6aa-17a8-faa1-a67f2dc9fa91')
uuid_string = str(uuid_obj)
print(uuid_string)  

Output:

f65c57f6-a6aa-17a8-faa1-a67f2dc9fa91

I have executed the above code and added the screenshot below.

Check if a String is a Valid UUID in Python convert UUID

The str() function returns a string in the form 12345678-1234-5678-1234-567812345678 where the 32 hexadecimal digits represent the UUID.

Read Convert Binary to Decimal in Python

2. Convert String to UUID

To convert a UUID string back to a UUID object, you can use the UUID() constructor:

from uuid import UUID

uuid_string = 'f65c57f6-a6aa-17a8-faa1-a67f2dc9fa91'
uuid_obj = UUID(uuid_string)
print(uuid_obj) 

Output:

f65c57f6-a6aa-17a8-faa1-a67f2dc9fa91

This creates a UUID object from the given string representation.

Read How to Split a String Every N Characters in Python?

Conclusion

In this tutorial, I explored how to check if a string is a valid UUID in Python. We covered the use of the UUID class from the uuid module to validate UUIDs and check their version. We also discussed how to convert between UUID objects and their string representations.

You may also like to read:

51 Python Programs

51 PYTHON PROGRAMS PDF FREE

Download a FREE PDF (112 Pages) Containing 51 Useful Python Programs.

pyython developer roadmap

Aspiring to be a Python developer?

Download a FREE PDF on how to become a Python developer.

Let’s be friends

Be the first to know about sales and special discounts.