How to Check if a String is a GUID in Python?

As a developer working on numerous projects for clients across the USA, I came across a situation where I needed to validate whether a given string followed the GUID format.  Python provides several ways to accomplish this and in this article, we will explore how to check if a string is a GUID in Python in different approaches with examples and a screenshot of executed example code.

What are GUIDs (Globally Unique Identifier)

A GUID is a 128-bit integer that is typically represented as a string of 32 hexadecimal digits, separated into five groups by hyphens. The standard format of a GUID looks like this: xxxxxxxx-xxxx-xxxx-xxxx-xxxxxxxxxxxx, where each x represents a hexadecimal digit (0-9 or a-f). For example, a valid GUID string would look like: "1e4a1f2b-7a4c-4c2e-9d8a-f662e6b9e1d5".

Read How to Convert a List to an Array in Python?

Check if a String is a GUID in Python

Let us see some approaches to check if a string is a GUID in Python.

1. Use Regular Expressions

One of the most common and efficient ways to check if a string is a GUID is by using regular expressions. Python’s built-in re module provides powerful tools for pattern matching and string validation.

Here’s an example of how to use a regular expression to validate a GUID:

import re

def is_valid_guid(guid):
    pattern = re.compile(r'^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$', re.I)
    return bool(pattern.match(guid))

# Example usage
guid1 = "1e4a1f2b-7a4c-4c2e-9d8a-f662e6b9e1d5"
guid2 = "invalid-guid-string"

print(is_valid_guid(guid1))  
print(is_valid_guid(guid2)) 

Output:

True
False

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

Check if a String is a GUID in Python

In this example, we define a function is_valid_guid that takes a string parameter guid. Inside the function, we compile a regular expression pattern using re.compile(). The pattern ^[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}$ matches the standard GUID format:

  • ^ asserts the start of the string
  • [0-9a-f]{8} matches exactly 8 hexadecimal digits
  • - matches a literal hyphen
  • [0-9a-f]{4} matches exactly 4 hexadecimal digits (repeated 3 times)
  • [0-9a-f]{12} matches exactly 12 hexadecimal digits
  • $ asserts the end of the string

The re.I flag makes the pattern case-insensitive, allowing both uppercase and lowercase hexadecimal digits.

Finally, we use pattern.match(guid) to check if the guid string matches the compiled pattern. The function returns True if the string is a valid GUID and False otherwise.

Check out How to Convert a Dictionary to an Array in Python?

2. Use the UUID Module

Python provides a built-in module uuid that offers functions for generating and working with UUIDs (Universally Unique Identifiers), which are similar to GUIDs. While the uuid module doesn’t have a direct function to validate GUIDs, you can leverage its functionality to achieve the same result.

Here’s an example of how to use the uuid module to check if a string is a valid GUID:

from uuid import UUID

def is_valid_guid(guid):
    try:
        UUID(guid)
        return True
    except ValueError:
        return False

# Example usage
guid1 = "1e4a1f2b-7a4c-4c2e-9d8a-f662e6b9e1d5"
guid2 = "invalid-guid-string"

print(is_valid_guid(guid1)) 
print(is_valid_guid(guid2))  

Output:

True
False

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

How to Check if a String is a GUID in Python

In this approach, we define the is_valid_guid function that takes a guid string as input. Inside the function, we use a try-except block to attempt to create a UUID object from the guid string. If the string is a valid GUID, the UUID object is created successfully, and the function returns True. If the string is not a valid GUID, a ValueError is raised, and the function returns False.

Read How to Read a Binary File into a Byte Array in Python?

Extract GUIDs from Strings

In some cases, you may have a long string that contains one or more GUIDs, and you want to extract them. You can achieve this using regular expressions as well.

Consider the following example:

import re

def extract_guids(text):
    pattern = re.compile(r'[0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12}', re.I)
    return pattern.findall(text)

# Example usage
log_message = "User John Doe (ID: 1e4a1f2b-7a4c-4c2e-9d8a-f662e6b9e1d5) logged in. Another user Jane Smith (ID: 8c3b2d1a-5e7f-4c9h-8g7i-6j5k4l3m2n1o) logged out."

guids = extract_guids(log_message)
print(guids)  

Output:

['1e4a1f2b-7a4c-4c2e-9d8a-f662e6b9e1d5', '8c3b2d1a-5e7f-4c9h-8g7i-6j5k4l3m2n1o']

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

Check if a String is a GUID in Python extract GUID

In this example, we have a log_message string that contains two GUIDs. The extract_guids function uses the regular expression pattern [0-9a-f]{8}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{4}-[0-9a-f]{12} to find all occurrences of GUIDs in the string. The findall() method returns a list of all matched GUIDs.

Check out How to Create Arrays in Python?

Conclusion

In this tutorial, we explored different methods to check if a string is a GUID in Python. We learned how to use regular expressions to validate and extract GUIDs from strings, as well as how to leverage the uuid module to check for valid GUIDs.

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.