Skip to content

Python string to enum | Example code

  • by

In Python, you can use the enum module to define an enumeration class, which is a set of named values. To convert a string to an enumeration value, you can use the getattr() function to get the value of the attribute with the corresponding name. The value returned is an enumeration value, which can be used like any other value in Python.

Example Convert string to Enum in Python

Simple example code.

from enum import Enum


class Build(Enum):
    debug = 200
    build = 400


print(Build['build'].value)

Output:

Python string to enum

The member names are case sensitive, so if user input is being converted you need to make sure the case matches:

from enum import Enum


class Build(Enum):
    debug = 200
    build = 400


an_enum = input('Which type of build?')
build_type = Build[an_enum.lower()]

print(build_type)

Output: Which type of build?

Another alternative (especially useful if your strings don’t map 1-1 to your enum cases) is to add a staticmethod to your Enum, e.g.:

import enum


class QuestionType(enum.Enum):
    MULTI_SELECT = "multi"
    SINGLE_SELECT = "single"

    @staticmethod
    def from_str(label):
        if label in ('single', 'singleSelect'):
            return QuestionType.SINGLE_SELECT
        elif label in ('multi', 'multiSelect'):
            return QuestionType.MULTI_SELECT
        else:
            raise NotImplementedError


print(QuestionType.from_str('single'))

Output: QuestionType.SINGLE_SELECT

Convert string to known Enum

from enum import Enum


class MyEnum(Enum):
    a = 'aaa'
    b = 123

print(MyEnum('aaa'), MyEnum(123))

Output: MyEnum.a MyEnum.b

Here’s the syntax for defining an enumeration class and converting a string to an enumeration value in Python:

from enum import Enum

# Define an enumeration class
class MyEnum(Enum):
    VALUE_1 = 'value1'
    VALUE_2 = 'value2'
    VALUE_3 = 'value3'

# Convert a string to an enumeration value
my_string = 'value2'
my_enum_value = MyEnum[my_string]

# Use the enumeration value
print(my_enum_value)  # Output: MyEnum.VALUE_2

Do comment if you have any doubts or suggestions on this Python Enumerate topic.

Note: IDE: PyCharm 2021.3.3 (Community Edition)

Windows 10

Python 3.10.1

All Python Examples are in Python 3, so Maybe its different from python 2 or upgraded versions.

Leave a Reply

Discover more from Tutorial

Subscribe now to keep reading and get access to the full archive.

Continue reading