How To Convert an Enum to a String in Python

Convert an Enum to a String in Python

To convert an enum to a string in Python, we have tested effectively with a combination of  str() function and the type() method to confirm. In addition, you can use add a __str__ method into your EnumCheck out the details below to get more information.

Convert an enum to a string in Python

Using the str() function and use type() method to confirm

To convert an enum to a string in Python, we can use the str() method to convert and use the type() method to make sure the enum is converted to a string.

Str() function

Syntax:

str(object, encoding=encoding, errors=errors)

Parameters: 

  • object: is any object, specifies the object to convert into a string.
  • encoding: is the encoding of the object. The default is UTF-8.
  • errors: specifies what to do if the decoding fails.

Return value: the return value is a string.

Type() method

Syntax:

type(object, bases, dict)

Parameters: 

  • object: The object whose type is to be returned.
  • bases: is a tuple that itemizes the base class.
  • dict: a dictionary that holds the namespaces for the class.

Return value: return value is the type of object in angular brackets.

Code Example:

Firstly we must import Enum. Then create the class Enum Animals. Secondly, we will use str() to convert the value of Enum Animals is int to string and use type() to print out the type of Enum after convert.

from enum import Enum
 
class Animals(Enum):
    SHARK = 1
    DOLPHIN = 2
    ELEPHANT = 3

for animal in Animals:
    print(type(animal.value))
    print(animal.name, animal.value)
    
print ("After converting Enum to string:")

# Use the str method to convert int to string 
for animal in Animals:
    print(type(str(animal.value)))
    print(animal.name, animal.value)

Output

<class 'int'>
SHARK 1
<class 'int'>
DOLPHIN 2
<class 'int'>
ELEPHANT 3
After converting Enum to string:
<class 'str'>
SHARK 1
<class 'str'>
DOLPHIN 2
<class 'str'>
ELEPHANT 3

Add a __str__ method into your Enum

Another way to convert an enum to a string in Python is you could add a __str__ method into the Enum and then convert the value int into a string.

Example:

from enum import Enum
 
class Animals(Enum):
    SHARK = 1
    DOLPHIN = 2
    ELEPHANT = 3

def __str__(self):
         return str(self.value)
         
for animal in Animals:
    print(type(__str__(animal)))
    print(__str__(animal))

Output

<class 'str'>
1
<class 'str'>
2
<class 'str'>
3

Summary

In this tutorial, we have explained how to convert an enum to a string in Python. We always hope this tutorial is helpful to you. Leave your comment here if you have any questions or comments to improve the article. Thanks for reading!

Maybe you are interested:

Leave a Reply

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