I have an enum
class Nationality:
Poland='PL'
Germany='DE'
France='FR'
...
Spain='ES'
I have 2 prototypes of methods:
# I want somethink like in c#
def convert_country_code_to_country_name(country_code):
print Enum.Parse(typeof(Nationality),country_code)
#this a second solution ,but it has a lot of ifs
def convert_country_code_to_country_name(country_code):
if country_code=='DE':
print Nationality.Germany #btw how to print here 'Germany', instead 'DE'
This is how I want call this method:
convert_country_code_to_country_name('DE') # I want here to print 'Germany'
How to implement it in python?
How to convert enum to string in python To print an enum member as a string we use the class and member name. In this example, we have enum class name FRUITS and have three members (APPLE = 1,ORANGE = 2,GRAPES = 3). We are printing enum members as FRUITS.APPLE by print () statement.
In this tutorial, we will look into different methods of using or implementing the enum in Python. The enum or enumeration is a special type of class representing a set of named constants of numeric type. Each named constant in the enum type has its own integer value, which depends on the set’s named constant position.
3. “ name ” keyword is used to display the name of the enum member. 4. Enumerations are iterable. They can be iterated using loops 5. Enumerations support hashing. Enums can be used in dictionaries or sets. 1. By value :- In this method, the value of enum member is passed. 2. By name :- In this method, the name of enum member is passed.
Enumerations are iterable. They can be iterated using loops 5. Enumerations support hashing. Enums can be used in dictionaries or sets. 1. By value :- In this method, the value of enum member is passed.
The best solution would be to create a dictionary right from the start. Your enum doesn't make sense in Python, its just unnecessarily complex. It looks like you are trying to write Java code, which is quite the opposite of what Python code is supposed to look like.
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