Python string to enum | Example code

Use the built-in Enum module to convert string to enum 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

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

Note: IDE: PyCharm 2021.1.3 (Community Edition)

Windows 10

Python 3.7

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


Leave a Reply

This site uses Akismet to reduce spam. Learn how your comment data is processed.