-1

Not a duplicate of: enum - getting value of enum on string conversion.

The question here is about how to the get Enum name (left part) converted to a string, not the value (right part).

With the following Enum:

class test(Enum):
    aa = 1
    bb = 2

I can do this:

v = test.aa
print(v)

and I get:

test.aa

but how do I convert v to a string?

martineau
  • 119,623
  • 25
  • 170
  • 301
Thomas
  • 10,933
  • 14
  • 65
  • 136

2 Answers2

0

Just access the name attribute on the object:

from enum import Enum

class test(Enum):
    aa = 1
    bb = 2

v = test.aa
print(v.name)

Output:

aa
ruohola
  • 21,987
  • 6
  • 62
  • 97
  • the str() way works too; coming from a c# background, I have a hard time to remember that everything in python is abbreviated! I think string, not str, length, not len, etc :) – Thomas Jul 26 '19 at 22:21
  • but this is exactly what I need: a string with test.aa, not '1' – Thomas Jul 26 '19 at 22:25
  • 1
    @Thomas Ahh, ok, then calling `var = str(v)` is just fine. – ruohola Jul 26 '19 at 22:25
0

You can cast the value or the enum itself

str(test.aa.value) == 1 .

str(test.aa) == 'test.aa' .

print(test.aa) will also cast it to a string

Kevin Welch
  • 1,488
  • 1
  • 9
  • 18