Convert an Enum to a String in Python

avatar

Borislav Hadzhiev

Last updated: Jun 17, 2022

banner

Check out my new book

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 name of enum print(Color.RED.name) # 👉️ RED # 👇️ get value of enum print(Color.RED.value) # 👉️ stop # 👇️ if enum value is int, you can convert it to str print(str(Color.RED.value)) # 👉️ stop
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.

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"

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.

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'
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')

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

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.