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 Enum. Check 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
str(object, encoding=encoding, errors=errors)
- 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(object, bases, dict)
- 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.
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)
<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.
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))
<class 'str'> 1 <class 'str'> 2 <class 'str'> 3
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:
- Ways To Split A String By Tab In Python
- Join The Keys Of A Dictionary Into A String In Python
- How To Replace Multiple Spaces With A Single Space In Python
Name of the university: HUSC