October DealsAmazon USOctober deal check: compare before you payAmazon US: current deals, useful picks and tech finds.Check DealsWindows FixRecommendedWindows errors stealing your time? Find the fix fastScan stability, cleanup and performance issues.Fix NowOctober DealsAmazon USDeal season is back - check today's better picksAmazon US: current deals, useful picks and tech finds.See Picks×
Skip to content
World desk2 min

How to Convert a String to an Enum in Python

In Python, call an enum class to look up a member by value or use square brackets to look it up by name. The choice determines the input format and exception to handle.
Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Use Color("red") when the string is an enum member’s value, and Color["RED"] when it is the member’s name. The two lookups can accept different strings and raise different exceptions when no match exists.

Choose lookup by value or by name

For a string-valued enum, calling the enum class looks up a member by its value. Square-bracket access looks up a member by its name, as shown in the Python Enum HOWTO and PEP 435.

from enum import Enum

class Color(Enum):
    RED = "red"
    GREEN = "green"

by_value = Color("red")  # Color.RED
by_name = Color["RED"]   # Color.RED

Both expressions return an enum member, not a plain string. Read its declared name with .name and its associated value with .value:

by_value.name   # "RED"
by_value.value  # "red"
What the input string represents Lookup Exception if no match exists
Member value, such as "red" Color("red") ValueError
Member name, such as "RED" Color["RED"] KeyError

The Python 3.12 enum reference documents the attributes and lookup behavior.

Free tools Windows power users keep installed

One-click scans. No signup required.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Handle input that does not match

Catch the exception for the lookup you chose at the point where untrusted or optional input enters the application. For example, return a fallback when a value lookup fails:

try:
    color = Color(raw_value)
except ValueError:
    color = None

For name lookup, catch KeyError instead. If invalid input should be rejected, let the lookup exception propagate or translate it into a clearer application-level error. Avoid catching broad Exception, which can conceal unrelated defects.

Make case and whitespace rules explicit

Name lookup uses the supplied name; do not assume it ignores case or surrounding whitespace. If the input contract allows case-insensitive matching and trimming, normalize before indexing:

color = Color[raw_name.strip().upper()]

This works only when enum names follow the same uppercase convention. Trimming and case-folding are application policies, not built-in case-insensitive enum lookup.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

When to use StrEnum

A regular Enum with string values already supports conversion with Color("red"). Choose StrEnum when members should also behave as strings in many contexts, rather than just to enable lookup. StrEnum was added in Python 3.11, so projects supporting earlier Python versions cannot rely on it.

The enum reference describes StrEnum as having members that are also strings and can be used in most of the same places as strings. Some standard-library locations check for an exact str type; use str(member) there if needed. String operations on a StrEnum member produce ordinary strings, not enum members. See the enum reference and Enum HOWTO.

Independent reader supportYour contribution helps us test, update, and keep practical guides available for everyone.Support on Ko-Fi

Understand duplicate values and aliases

By default, two enum names may share a value. The later name is an alias: looking up the shared value returns the canonical member, normal iteration omits aliases, and the read-only __members__ mapping includes every name. If duplicate values should make the enum definition invalid, apply @unique:

from enum import Enum, unique

@unique
class Color(Enum):
    RED = "red"
    GREEN = "green"

Alias behavior and uniqueness are described in the Enum HOWTO, enum reference, and PEP 435.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

Product prices and availability are accurate as of the date/time indicated and are subject to change. Any price and availability information displayed on Amazon at the time of purchase will apply.

Leave a Reply

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

What’s actually slowing this PC down?

Pick the symptom - the matching free tool is one click away.

Special offer. See more information about Outbyte and uninstall instructions. Please review EULA and Privacy policy.

More from the Wire

  1. World desk4 min
    How to Spot an AI Voice Scam Before Sending MoneyDon’t rely on how a caller sounds. Pause, call back through a known number, and verify the emergency with another trusted person before sending money.
  2. Mountain View desk4 min
    Google’s SynthID Detector: How to Check AI-Generated Images, Video and AudioGoogle’s SynthID Detector looks for an embedded watermark in supported images, video and audio. Here is what its results do—and do not—show.
  3. Redmond desk20 min
    How to create a link to File or Folder in Windows 11Windows 11 gives you several ways to point to a file or folder without moving or duplicating it. You can create a desktop shortcut,…
Recommended PC Tool
Recommended PC Tool
Outdated Drivers Are Slowing You DownFree scan - exact matches
PC Slower Than It Used to Be?Free scan - under a minute

Two free Windows tools

One Free Minute Could Fix That PC

Before you go - each of these free tools takes about a minute and tackles what quietly slows a Windows PC down.

Special offer. View Outbyte info, uninstall instructions, EULA, and Privacy Policy.