How To Convert A String To An Enum In Python

Convert a String to an Enum in Python

If you don’t know how to convert a string to an enum in Python. Rest assured, today we will show you how to do it. Read on to learn more.

How to convert a string to an enum in Python?

Before starting the main content, let’s quickly learn about the enum in Python.

Enum is the keyword used to declare an enumeration type (Enumeration). An enumeration is a set of user-defined constants. It supports users to group constants and shares a common name (usually, these constants will be related to each other, for example, states of a thing, properties of an object, etc…)

First of all, we have to import Enum from the enum with a line of code like this:

from enum import Enum

Enum syntax:

class EnumName(Enum):
  # List of related constants

Description:

This syntax is similar to the syntax of class. In addition, an enum contains a list of related constants in the form of names and values.

We will show you two ways to convert a String to an Enum in Python.

Cast the data type of a string to an enum

This is the same as casting a string to an int. The only difference is that we have to define a constant for that string in the enum. Observe the code below to understand more.

from enum import Enum

class Bookmark(Enum):
    LEARNSHAREIT = "learnshareit.com"
    GOOGLE = "google.com"
    YOUTUBE = "youtube.com"
    AMAZONE = "amazone.com"

# Url string
url1 = "learnshareit.com"
url2 = "facebook.com"

# Convert to enum and check
print(type(Bookmark(url1)))

# print(type(Bookmark(url2))) --> Error: 'facebook.com' is not a valid value

Output:

<enum 'Bookmark'>

Use for loop

You can learn more about the for loop syntax here.

The idea here is that we iterate through the elements of the enum using a for loop to compare a string with the values of the elements in the enum. Then, if it exists, we will return the enum element itself.

from enum import Enum

class Bookmark(Enum):
    LEARNSHAREIT = "learnshareit.com"
    GOOGLE = "google.com"
    YOUTUBE = "youtube.com"
    AMAZONE = "amazone.com"

# Url string
url1 = "learnshareit.com"
url2 = "facebook.com"

def convert_to_enum(string):
    for bookmark in Bookmark:
        if string == bookmark.value:
            return bookmark
        else:
            return f"can not convert {string} to Enum"

# Convert to enum
print(convert_to_enum(url1))
print(convert_to_enum(url2))

Output:

Bookmark.LEARNSHAREIT
can not convert facebook.com to Enum

Summary

This article has introduced you to about enums and how to convert a string to an enum in Python. You just understand that converting a string to an enum is as simple as converting a string to an int, except that the string must be predefined. We hope this article is helpful to you. Thank you for reading!

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *