1

python 3.8.2 :

I have tried to get a string, created with join from an enum.

import enum

# import aenum
# https://pypi.org/project/aenum/


class ELEMENTS(enum.Enum):
    L = ("L", "light", "licht")
    P = ("P", "power connectors", "stopcontacten")
    vM = ("vM", "ventilation motor", "ventilatie motor")
    cvM = ("cvM", "CV motor", "CV motor")
    S = ("S", "switch", "schakelaar")
    V = ("V", "valve", "klep")


ELEMENTS_list = []
print(len(ELEMENTS))
for s in ELEMENTS:
    ELEMENTS_list.append(s.value[0])

regexELEMENTS = "[" + ("|".join(ELEMENTS_list)) + "]"

returns, as result :

[L|P|vM|cvM|S|V]

Update on feedback of 'VPfB' - thanks

regexELEMENTS = "(" + ("|".join(ELEMENTS_list)) + ")"

returns, the wanted result :

(L|P|vM|cvM|S|V)

By my humble opinion the code would be more proper, if I could do it immediately from the enum.

...

print("|".join(ELEMENTS.value[0]))

returns error :

... in __getattr__
raise AttributeError(name) from None

an other approach :

print("|".join(ELEMENTS))

returns error :

TypeError: sequence item 0: expected str instance, ELEMENTS found

In the second step I'll use the variable 'regexELEMENTS' in a regular expression. '{regexELEMENTS}'

Based on this question : How to use a variable inside a regular expression?

What I'm missing here ... or do I wrong?

Hope to understand, what I'm doing wrong ...

Suggestions to make the code better are more then welcome.

Thanks

kris
  • 392
  • 4
  • 16

1 Answers1

2

Not sure if you want to use the names or the value[0] strings which happen to be the same in your example. Choose one:

print("|".join(ELEMENTS.__members__))  # using names

or:

print("|".join(m.value[0] for m in ELEMENTS))   # using value[0]

This answer is based mainly on enum iteration docs. I have omitted [ and ] for brevity (BTW, I think you want ( and ) to build an usable regexp)

VPfB
  • 14,927
  • 6
  • 41
  • 75
  • Thank you very much ... for loops in one line. And correctly it has to be `(` and `)` instead of `[` and `]` `print("|".join(ELEMENTS.__members__)) # using names` is the best way ***. I have already deleted the first index `ELEMENTS.value[0]` in my code. – kris Mar 26 '21 at 08:08
  • 1
    I'm glad I could help. The "for loops in one line" have an official name: https://docs.python.org/3/howto/functional.html#generator-expressions-and-list-comprehensions – VPfB Mar 26 '21 at 08:09
  • Dear @VPfB, thanks for the answer ... I just have read your profile "I'm the author of a free open-source Python library that has zero users except me.)" ... **unknown is unloved**. So would you be so kind ... to add it in your profile ... maybe there a lot of members which are looking for such kind of library ... – kris Mar 29 '21 at 07:02
  • @kris Oh, my library ... well, thanks for asking, but it is not hidden. It is available on github and on PyPi for more than a year and it really looks like nobody needs it. Judge yourself, the name is "edzed". – VPfB Mar 29 '21 at 08:03