How to Convert String to Enum in Python

Strings in Python are commonly used to represent values like status codes, settings, or user selections. However, when working with structured data or making comparisons, using Enums provides better organization and error handling.

For example, you might receive user input as a string like “COMPLETED” but want to treat it as an Enum value in your program.

In such situations, it becomes essential to convert a string to an Enum. This allows you to take advantage of Enum features.

Enums in Python

Before getting into string conversion, let’s quickly understand Enums. Added in Python 3.4, the enum module provides a way to create sets of symbolic names bound to unique values. They’re particularly useful for defining constants and categorical values.

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

Enums provide type safety, better readability, and help catch errors during development rather than at runtime.

Read How to Convert a String to Lowercase in Python?

Convert String to Enum in Python

Let me explain to you the important methods to convert string to enum in Python.

Method 1: Use the getattr() Method

The most simple approach to convert a string to an Enum in Python is using the built-in getattr() function. This method is widely recognized as the standard solution.

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

# Convert string to Enum
color_name = "RED"
color_enum = getattr(Color, color_name)

print(color_enum) 
print(color_enum.value)

Output:

Color.RED
1

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

Convert String to Enum in Python

Handle Invalid Strings

One issue with getattr() is that it raises an AttributeError if the Python string doesn’t match any Enum member. Here’s how to handle this gracefully:

try:
    color_enum = getattr(Color, color_name)
except AttributeError:
    print(f"'{color_name}' is not a valid Color")
    # Optional: set a default value
    color_enum = Color.RED

Check out How to Concatenate String and Int in Python?

Method 2: Use Enum(value) for Reverse Lookup

Sometimes you might have the value and want to get the Enum member in Python. This is a bit different from our main topic but useful to know:

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
    
# Finding Enum member by value
value = 2
color_enum = Color(value)
print(color_enum)

Output:

Color.GREEN

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

Python String to Enum

Read How to Convert Datetime to String in Python?

Method 3: Create a Custom Conversion Method

This approach is especially useful when working in large applications where robust error handling and user-friendly messages are important.

from enum import Enum
class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3
    
class ColorConverter:
    @staticmethod
    def from_string(color_name, case_sensitive=True):
        try:
            if case_sensitive:
                return getattr(Color, color_name)
            else:
                return getattr(Color, color_name.upper())
        except AttributeError:
            valid_colors = [c.name for c in Color]
            raise ValueError(f"Invalid color '{color_name}'. Valid options are: {valid_colors}")
#usage
red = ColorConverter.from_string("RED")
print(f"Red color enum: {red}")

green = ColorConverter.from_string("green", case_sensitive=False)
print(f"Green color enum: {green}")

Output:

Red color enum: Color.RED
Green color enum: Color.GREEN

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

How to Convert String to Enum in Python

Using a custom conversion method allows you to gracefully manage input variations and errors when mapping strings to enums.

Check out How to Split String by Whitespace in Python?

Method 4: Use Enum Auto-Conversion

The Enum module in Python is quite powerful, and with a bit of customization, we can create an Enum subclass that handles string conversion automatically:

from enum import Enum

class StringEnum(str, Enum):
    """An Enum that can be created from a string."""
    @classmethod
    def from_string(cls, s):
        try:
            return cls[s]
        except KeyError:
            raise ValueError(f"{s} is not a valid {cls.__name__}")

class Fruit(StringEnum):
    APPLE = "apple"
    BANANA = "banana"
    ORANGE = "orange"

# Usage
fruit = Fruit.from_string("APPLE")
print(fruit)  # Output: Fruit.APPLE

Read How to Remove HTML Tags from a String in Python?

Method 5: Use a Dictionary Mapping

For scenarios where Enum names might not match the input strings exactly (like handling different formats or abbreviations), a dictionary mapping in Python can be useful:

from enum import Enum

class State(Enum):
    CALIFORNIA = 1
    NEW_YORK = 2
    TEXAS = 3
    FLORIDA = 4

# Mapping of possible string inputs to Enum members
state_mapping = {
    "CA": State.CALIFORNIA,
    "California": State.CALIFORNIA,
    "calif": State.CALIFORNIA,
    "NY": State.NEW_YORK,
    "New York": State.NEW_YORK,
    "TX": State.TEXAS,
    "Texas": State.TEXAS,
    "FL": State.FLORIDA,
    "Florida": State.FLORIDA
}

def get_state_from_string(state_string):
    normalized_string = state_string.strip()
    return state_mapping.get(normalized_string, None)

# Usage
state = get_state_from_string("CA")
print(state)  # Output: State.CALIFORNIA

Handle Case Sensitivity in Python String to Enum Conversion

Case sensitivity is often a challenge when converting strings to Enums. Here are different approaches to handle this:

Check out How to Convert an Object to a String in Python?

Option 1: Case-Insensitive Lookup

This function takes an Enum class and a string name, loops through all the members of the enum, and compares each member’s name with the provided string in a lowercase format.

def get_enum_case_insensitive(enum_class, name):
    for enum_member in enum_class:
        if enum_member.name.lower() == name.lower():
            return enum_member
    return None

# Usage
color = get_enum_case_insensitive(Color, "red")  # Returns Color.RED

We define a helper function called get_enum_case_insensitive() that allows us to perform case-insensitive lookups on Enum members.

Option 2: Create a Case-Insensitive Enum Class

The custom implementation checks if the input is a string and compares it to the names of enum members in a case-insensitive way.

class CaseInsensitiveEnum(Enum):
    @classmethod
    def _missing_(cls, value):
        if isinstance(value, str):
            for member in cls:
                if member.name.lower() == value.lower():
                    return member
        return None

class Weekday(CaseInsensitiveEnum):
    MONDAY = 1
    TUESDAY = 2
    WEDNESDAY = 3
    THURSDAY = 4
    FRIDAY = 5

# Usage
day = Weekday("monday")  # Returns Weekday.MONDAY

We create a custom base class named CaseInsensitiveEnum that inherits from Python’s built-in Enum.

Read How to Extract Numbers from a String in Python?

Extend Enum Functionality

Extending Python’s built-in Enum class allows us to add extra functionality that makes working with enums more convenient.

from enum import Enum, auto

class ExtendedEnum(Enum):
    @classmethod
    def list_names(cls):
        return [c.name for c in cls]

    @classmethod
    def list_values(cls):
        return [c.value for c in cls]

    @classmethod
    def from_string(cls, s):
        try:
            return getattr(cls, s)
        except AttributeError:
            return None

class Planet(ExtendedEnum):
    MERCURY = auto()
    VENUS = auto()
    EARTH = auto()
    MARS = auto()

# Usage
print(Planet.list_names())  # ['MERCURY', 'VENUS', 'EARTH', 'MARS']
earth = Planet.from_string("EARTH")  # Planet.EARTH

This approach promotes cleaner, more maintainable code when working with enums across your application.

In this article, I explained how to convert string to enum in Python. I explained methods like using the getattr() method, using enum(value) for reverse lookup, creating a custom conversion method, enum auto-conversion, and using dictionary mapping. I also covered how to handle case sensitivity while converting and extending enum functionality.

You may 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.