We can convert an enum to string by calling the ToString() method of an Enum.
Use the Enum. IsDefined() method to check if a given string name or integer value is defined in a specified enumeration. Thus, the conversion of String to Enum can be implemented using the Enum. Parse ( ) and Enum.
The Parse method in Enum converts the string representation of the name or numeric value of enum constants to an equivalent enumerated object.
To convert string to enum use static method Enum. Parse. Parameters of this method are enum type, the string value and optionally indicator to ignore case.
You are printing the enum object. Use the .value
attribute if you wanted just to print that:
print(D.x.value)
See the Programmatic access to enumeration members and their attributes section:
If you have an enum member and need its name or value:
>>> >>> member = Color.red >>> member.name 'red' >>> member.value 1
You could add a __str__
method to your enum, if all you wanted was to provide a custom string representation:
class D(Enum):
def __str__(self):
return str(self.value)
x = 1
y = 2
Demo:
>>> from enum import Enum
>>> class D(Enum):
... def __str__(self):
... return str(self.value)
... x = 1
... y = 2
...
>>> D.x
<D.x: 1>
>>> print(D.x)
1
I implemented access using the following
class D(Enum):
x = 1
y = 2
def __str__(self):
return '%s' % self.value
now I can just do
print(D.x)
to get 1
as result.
You can also use self.name
in case you wanted to print x
instead of 1
.
If you are going to print value using f-string then you can inherit your enum from both Enum
and str
. For instance:
from enum import Enum
class D(str, Enum):
x = 1
y = 2
print(D.x)
print(f"{D.x}")
Outputs:
D.x
1
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With