How to convert Enum to string in Python : 4 Methods

Enum allows you to create enumrerations. It means you can create symbolic names that is unique and constant. If you wants to convert enum to string in python then this post is for you.

Methods to convert Enum to string in Python

To convert a Python enum to a string, you have a few options. Here are three common methods you can use:

1. The str() function:

You can use the built-in str() function to convert an enum to a string in python. This method relies on the default __str__() method implemented in the enum.Enum class, which returns the name of the enum member as a string.

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

color = Color.RED
color_str = str(color)
print(color_str)

Output

'Color.RED'

2. The name attribute:

Each enum member has a name attribute that represents its name as a string. You can directly access this attribute to obtain the string representation of the enum.

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

color = Color.GREEN
color_str = color.name
print(color_str)

Output

'GREEN'

3. The value attribute with str() function:

If you want to convert the enum’s associated value to a string, you can access the value attribute of the enum member and then use the str() function to convert it to a string.

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

color = Color.BLUE
color_value_str = str(color.value)
print(color_value_str) 

Output

'3'

4. Using format() or f-strings:

You can use Python’s string formatting methods, such as format() or f-strings, to convert an enum to a string. These methods allow you to incorporate the enum’s properties or attributes into the resulting string.

from enum import Enum

class Color(Enum):
    RED = 1
    GREEN = 2
    BLUE = 3

color = Color.GREEN
color_str = "The color is {}".format(color.name)
print(color_str)

color_str = f"The color is {color}"
print(color_str)
'The color is GREEN'
'The color is Color.GREEN'

Conclusion

In this post you have learned what are enums and how to easily convert enum to string. The above methods should cover most use cases when it comes to converting a Python enum to a string.

Hi, I am CodeTheBest. Here you will learn the best coding tutorials on the latest technologies like a flutter, react js, python, Julia, and many more in a single place.

SPECIAL OFFER!

This Offer is Limited! Grab your Discount!
15000 ChatGPT Prompts
Offer Expires In:
close-link