Borislav Hadzhiev
Last updated: Jun 17, 2022
Check out my new book
To convert an enum to a string in Python:
Color.RED.name
.Color.RED.value
.str()
class to convert the value to a string.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
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.
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.
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'
You can use a simple for
loop if you need to iterate over an enum.
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.
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.