Convert an Enum to a String and vice versa in Python

avatar
Borislav Hadzhiev

Last updated: Apr 8, 2024
8 min

banner

# Table of Contents

  1. Convert an Enum to a String in Python
  2. Convert a String to an Enum in Python
  3. Convert an Enum to an Integer in Python
  4. Convert an Integer to an Enum in Python
  5. Convert an Enum to JSON in Python

# Convert an Enum to a String in Python

To convert an enum to a string in Python:

  1. Access the name of the enum, e.g. Color.RED.name.
  2. Access the value of the enum, e.g. Color.RED.value.
  3. Optionally, use the str() class to convert the value to a string.
main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' # ๐Ÿ‘‡๏ธ Human-readable string representation print(Color.RED) # ๐Ÿ‘‰๏ธ Color.RED # ๐Ÿ‘‡๏ธ repr() shows the value as well print(repr(Color.RED)) # ๐Ÿ‘‰๏ธ <Color.RED: 'stop'> # ๐Ÿ‘‡๏ธ Get the name of enum print(Color.RED.name) # ๐Ÿ‘‰๏ธ RED # ๐Ÿ‘‡๏ธ Get the value of enum print(Color.RED.value) # ๐Ÿ‘‰๏ธ stop # ๐Ÿ‘‡๏ธ If the enum value is int, you can convert it to str print(str(Color.RED.value)) # ๐Ÿ‘‰๏ธ stop

convert enum to string

The code for this article is available on GitHub
You can use the name and value properties on an enum member to get the enum's name and value.

If the value is not a string and you need to convert it to one, pass it to the str() class.

main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' # ๐Ÿ‘‡๏ธ if enum value is int, you can convert it to str print(str(Color.RED.value)) # ๐Ÿ‘‰๏ธ stop

passing the value to str class

The str() class returns the string representation of the supplied value.

# Implementing the __str__ method in the Enum class

Alternatively, you can implement the __str__() method in the class.

main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' def __str__(self): return str(self.value) print(Color.RED) # ๐Ÿ‘‰๏ธ "stop"

implement str method in enum class

The code for this article is available on GitHub

The __str__() method is called by str(object) and the built-in functions format() and print() and returns the informal string representation of the object.

Now you can get the value of the enum directly, without accessing the value attribute on the enum member.

# Using square bracket notation to access Enum members

You can also use square brackets to access enum members.

main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' name = 'RED' print(Color[name].value) # ๐Ÿ‘‰๏ธ 'stop' print(Color['RED'].value) # ๐Ÿ‘‰๏ธ 'stop'

using square bracket notation to access enum members

The code for this article is available on GitHub
This is useful when you don't know the name of the enum member ahead of time (because it's read from a file or fetched from an API).

You can use a simple for loop if you need to iterate over an enum.

main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' for color in Color: print(color) print(color.name, color.value)

You can use a list comprehension to check if a specific value is in an enum.

main.py
from enum import Enum class Color(Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' # ๐Ÿ‘‡๏ธ Check enum member type print(type(Color.RED)) # ๐Ÿ‘‰๏ธ <enum 'Color'> # ๐Ÿ‘‡๏ธ Check if member belongs to Enum print(isinstance(Color.RED, Color)) # ๐Ÿ‘‰๏ธ True values = [member.value for member in Color] print(values) # ๐Ÿ‘‰๏ธ ['stop', 'go', 'get ready'] if 'stop' in values: # ๐Ÿ‘‡๏ธ this runs print('stop is in values')
The code for this article is available on GitHub

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

# Convert a String to an Enum in Python

To convert a string to an enum in Python:

  1. Import the Enum class from the enum module.
  2. Declare an enum by extending the Enum class.
  3. Assign class properties on the enum class.
main.py
from enum import Enum class Sizes(Enum): SMALL = 'sm' MEDIUM = 'md' LARGE = 'lg' # ๐Ÿ‘‡๏ธ Human-readable string representation print(Sizes.MEDIUM) # ๐Ÿ‘‰๏ธ Sizes.MEDIUM # ๐Ÿ‘‡๏ธ repr() shows the value as well print(repr(Sizes.MEDIUM)) # ๐Ÿ‘‰๏ธ <Sizes.MEDIUM: 'md'> # ๐Ÿ‘‡๏ธ Get the name of the enum print(Sizes.MEDIUM.name) # ๐Ÿ‘‰๏ธ MEDIUM # ๐Ÿ‘‡๏ธ Get the value of the enum print(Sizes.MEDIUM.value) # ๐Ÿ‘‰๏ธ md # ๐Ÿ‘‡๏ธ If the enum value is int, you can convert it to str print(str(Sizes.MEDIUM.value)) # ๐Ÿ‘‰๏ธ md # ๐Ÿ‘‡๏ธ Access enum member using a string print(Sizes['LARGE'].value) # ๐Ÿ‘‰๏ธ lg

converting a string to an enum in python

The code for this article is available on GitHub

Enums are created using the class syntax and enum members (e.g. Sizes.SMALL) can be anything: int, str, etc.

The example creates an enumeration with 3 members that all have values of type string.

You can use the name and value properties on an enum member to get the enum's name and value.

# Using bracket notation to get the enum's name and value

You can also use square brackets to access enum members.

main.py
from enum import Enum class Sizes(Enum): SMALL = 'sm' MEDIUM = 'md' LARGE = 'lg' name = 'MEDIUM' print(Sizes[name].value) # ๐Ÿ‘‰๏ธ md print(Sizes['LARGE'].value) # ๐Ÿ‘‰๏ธ lg
The code for this article is available on GitHub
This is useful when you don't know the name of the enum member ahead of time (because it's read from a file or fetched from an API).

# Accessing an enum with a string from user input

Here is an example that takes a string from user input and uses it to access an enum member.

main.py
from enum import Enum class Sizes(Enum): SMALL = 'sm' MEDIUM = 'md' LARGE = 'lg' name = input('SMALL, MEDIUM or LARGE: ') print(name) # ๐Ÿ‘‰๏ธ small print(Sizes[name.upper()]) # ๐Ÿ‘‰๏ธ Sizes.SMALL print(Sizes[name.upper()].value) # ๐Ÿ‘‰๏ธ sm

You can use a simple for loop if you need to iterate over an enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 'sm' MEDIUM = 'md' LARGE = 'lg' for size in Sizes: print(size) print(size.name, size.value)

You can use a list comprehension to check if a specific value is in an enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 'sm' MEDIUM = 'md' LARGE = 'lg' # ๐Ÿ‘‡๏ธ check enum member type print(type(Sizes.MEDIUM)) # ๐Ÿ‘‰๏ธ <enum 'Sizes'> # ๐Ÿ‘‡๏ธ check if member belongs to Enum print(isinstance(Sizes.MEDIUM, Sizes)) # ๐Ÿ‘‰๏ธ True values = [member.value for member in Sizes] print(values) # ๐Ÿ‘‰๏ธ ['sm', 'md', 'lg'] if 'md' in values: # ๐Ÿ‘‡๏ธ this runs print('md is in values')

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

# Convert an Enum to an Integer in Python

Use the IntEnum class from the enum module to convert an enum to an integer in Python.

You can use the auto() class if the exact value is unimportant. To get a value of an enum member, use the value attribute on the member.

main.py
from enum import IntEnum class Sizes(IntEnum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes(1)) # ๐Ÿ‘‰๏ธ Sizes.SMALL print(Sizes.SMALL.name) # ๐Ÿ‘‰๏ธ SMALL print(Sizes.SMALL.value) # ๐Ÿ‘‰๏ธ 1
The code for this article is available on GitHub

The Sizes(1) syntax allows us to pass an integer to the class and get the corresponding enum member.

This is useful when you don't know the name of the enum member ahead of time (because it's read from a file or fetched from an API).

You can also use the auto() class if the exact value of the enum members is unimportant.

main.py
from enum import IntEnum, auto class Sizes(IntEnum): SMALL = auto() MEDIUM = auto() LARGE = auto() # ๐Ÿ‘‡๏ธ [<Sizes.SMALL: 1>, <Sizes.MEDIUM: 2>, <Sizes.LARGE: 3>] print(list(Sizes)) print(Sizes.SMALL.name) # ๐Ÿ‘‰๏ธ SMALL print(Sizes.SMALL.value) # ๐Ÿ‘‰๏ธ 1

By default, the initial value when using the auto class starts at 1.

Extending from the IntEnum class is useful if you have to compare members of the enum to integers.

main.py
from enum import IntEnum class Sizes(IntEnum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes.SMALL == 1) # ๐Ÿ‘‰๏ธ True print(Sizes.MEDIUM == 2) # ๐Ÿ‘‰๏ธ True

Alternatively, you can use the more generic Enum class from the enum module.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes(1)) # ๐Ÿ‘‰๏ธ Sizes.SMALL print(Sizes.SMALL.name) # ๐Ÿ‘‰๏ธ SMALL print(Sizes.SMALL.value) # ๐Ÿ‘‰๏ธ 1
The code for this article is available on GitHub

You can also use square brackets to programmatically access enum members.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 name = 'MEDIUM' print(Sizes[name].value) # ๐Ÿ‘‰๏ธ 2 print(Sizes['SMALL'].value) # ๐Ÿ‘‰๏ธ 1

You can use a simple for loop if you need to iterate over an enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 for size in Sizes: print(size) print(size.name, size.value)

You can use a list comprehension to check if a specific value is in an enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 # ๐Ÿ‘‡๏ธ check enum member type print(type(Sizes.MEDIUM)) # ๐Ÿ‘‰๏ธ <enum 'Sizes'> # ๐Ÿ‘‡๏ธ check if member belongs to Enum print(isinstance(Sizes.MEDIUM, Sizes)) # ๐Ÿ‘‰๏ธ True values = [member.value for member in Sizes] print(values) # ๐Ÿ‘‰๏ธ [1, 2, 3] if 2 in values: # ๐Ÿ‘‡๏ธ this runs print('2 is in values')

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

# Convert an Integer to an Enum in Python

Use parentheses to convert an integer to an enum in Python, e.g. print(Sizes(1)).

You can pass the integer value of an enum member as an argument to the class and it will return the enum member.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes(1)) # ๐Ÿ‘‰๏ธ Sizes.SMALL print(Sizes(2)) # ๐Ÿ‘‰๏ธ Sizes.MEDIUM print(Sizes(3)) # ๐Ÿ‘‰๏ธ Sizes.LARGE print(Sizes(1).name) # ๐Ÿ‘‰๏ธ SMALL print(Sizes(1).value) # ๐Ÿ‘‰๏ธ 1
The code for this article is available on GitHub

The Sizes(1) syntax allows us to pass an integer to the class and get the corresponding enum member.

This is useful when you don't know the name of the enum member ahead of time (because it's read from a file or fetched from an API).

You could also extend from the IntEnum class if you have to compare members of the enum to integers.

main.py
from enum import IntEnum class Sizes(IntEnum): SMALL = 1 MEDIUM = 2 LARGE = 3 print(Sizes(1)) # ๐Ÿ‘‰๏ธ Sizes.SMALL print(Sizes(2)) # ๐Ÿ‘‰๏ธ Sizes.MEDIUM print(Sizes(3)) # ๐Ÿ‘‰๏ธ Sizes.LARGE print(Sizes(1).name) # ๐Ÿ‘‰๏ธ SMALL print(Sizes(1).value) # ๐Ÿ‘‰๏ธ 1 print(Sizes.SMALL == 1) # ๐Ÿ‘‰๏ธ True print(Sizes.MEDIUM == 2) # ๐Ÿ‘‰๏ธ True

You can also use square brackets to programmatically access enum members.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 name = 'MEDIUM' print(Sizes[name].value) # ๐Ÿ‘‰๏ธ 2 print(Sizes['SMALL'].value) # ๐Ÿ‘‰๏ธ 1

Here is an example that takes user input and uses it to access an enum member.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 value = input('Pick size - 1, 2 or 3: ') print(value) # ๐Ÿ‘‰๏ธ 2 print(Sizes(int(value))) # ๐Ÿ‘‰๏ธ Sizes.MEDIUM print(Sizes(int(value)).name) # ๐Ÿ‘‰๏ธ MEDIUM print(Sizes(int(value)).value) # ๐Ÿ‘‰๏ธ 2

You can use a simple for loop if you need to iterate over an enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 for size in Sizes: print(size) print(size.name, size.value)
The code for this article is available on GitHub

You can use a list comprehension to check if a specific value is in an enum.

main.py
from enum import Enum class Sizes(Enum): SMALL = 1 MEDIUM = 2 LARGE = 3 # ๐Ÿ‘‡๏ธ check enum member type print(type(Sizes.MEDIUM)) # ๐Ÿ‘‰๏ธ <enum 'Sizes'> # ๐Ÿ‘‡๏ธ check if member belongs to Enum print(isinstance(Sizes.MEDIUM, Sizes)) # ๐Ÿ‘‰๏ธ True values = [member.value for member in Sizes] print(values) # ๐Ÿ‘‰๏ธ [1, 2, 3] if 2 in values: # ๐Ÿ‘‡๏ธ this runs print('2 is in values')

List comprehensions are used to perform some operation for every element, or select a subset of elements that meet a condition.

# Convert an Enum to JSON in Python

To convert an enum to JSON, extend from the str or int classes when declaring your enumeration class.

You will then be able to serialize the enum members to JSON directly by using the json.dumps() method.

main.py
from enum import Enum import json # ๐Ÿ‘‡๏ธ subclass str class first, then Enum class Color(str, Enum): RED = 'stop' GREEN = 'go' YELLOW = 'get ready' my_json = json.dumps(Color.RED) print(my_json) # ๐Ÿ‘‰๏ธ "stop" my_str = json.loads(my_json) print(my_str) # ๐Ÿ‘‰๏ธ 'stop'

The Color class is a subclass of both str() and Enum.

You can use the int class to create an enum with constants that are also subclasses of int.

main.py
from enum import Enum import json class Color(int, Enum): RED = 1 GREEN = 2 YELLOW = 3 my_json = json.dumps(Color.RED) print(my_json) # ๐Ÿ‘‰๏ธ "1" my_int = json.loads(my_json) print(my_int) # ๐Ÿ‘‰๏ธ 1

This is very similar to using the IntEnum class from the enum module.

main.py
from enum import IntEnum import json class Color(IntEnum): RED = 1 GREEN = 2 YELLOW = 3 my_json = json.dumps(Color.RED) print(my_json) # ๐Ÿ‘‰๏ธ "1" my_int = json.loads(my_json) print(my_int) # ๐Ÿ‘‰๏ธ 1
The code for this article is available on GitHub

Instead of extending from int and Enum, we extended from the IntEnum class to achieve the same result.

Note that there are some rules when working with derived enumerations:

  1. When subclassing Enum, specify mix-in types before the Enum class.
  2. While Enum can have members of any type, once additional types are mixed, all the members in the enum must have values of the specified type (e.g. int).

# Additional Resources

You can learn more about the related topics by checking out the following tutorials:

I wrote a book in which I share everything I know about how to become a better, more efficient programmer.
book cover
You can use the search field on my Home Page to filter through all of my articles.

Copyright ยฉ 2024 Borislav Hadzhiev