How To Compare A String With An Enum In Python

How to compare a string with an Enum in Python

How to compare a string with an Enum in Python is a frequently asked question among new programmers. The article below will answer all your questions with two operators are == and is.

To compare a string with an Enum in Python

Use == operator 

Please refer to how I compare a string with an Enum in Python below. I will explain it later.

# Import Enum
from enum import Enum

# Init a class Animals
class Animals(str, Enum):
	NUMBER1 = 'cat'
	NUMBER2 = 'dog'
	NUMBER3 = 'cow'

# Init myAnimal
myAnimal = 'cat'

# Compare myAnimal with Enum1
if myAnimal == Animals.NUMBER1:    
	# Show the result
	print("Value of the first animal is: " + Animals.NUMBER1.value)

First, I instantiate an Animals class with Enums as parameters. Then I initialize a variable is myAnimal, with a data type string.

Next, I compare two values. If true, then I will print out the value of that variable.

Output:

Value of the first animal is: cat

Comparison operator == has been used in the problem. It is pretty easy to use.

Same example, if not the value you need, I will give a message like this:

# Import Enum
from enum import Enum

# Init a class Animals
class Animals(str, Enum):
	NUMBER1 = 'cat'
	NUMBER2 = 'dog'
	NUMBER3 = 'cow'

# Init myAnimal
myAnimal = 'fish'

# Compare myAnimal with Enum1
if myAnimal == Animals.NUMBER1:
    
	# Show the result
	print("Value of the first animal is: " + Animals.NUMBER1.value)
else:
	print("This is not match!!")

Output

This is not match!!

Use is operator 

The is operator differs from the == operator in comparing an enum with a string in that when using this operator, I must get the enum’s value straight to use it.

With the above example type, I can change it a bit with the use of the is operator as follows:

# Import Enum
from enum import Enum

# Init a class People
class People(str, Enum):
	PERSON1 = 'John'
	PERSON2 = 'Tommy'
	PERSON3 = 'Lucy'

# Init myName
myName = 'Lucy'

# Use is operator to compare
if myName is People.PERSON3.value:
    
	# Show the result
	print("Name of the first person is: " + People.PERSON3.value)

Output

Name of the first person is: Lucy

The difference between the == and is operator has a specific meaning. One side will compare the value, and the other will compare whether the reference object is in the same place. Depending on the requirements of the project, these two operators will be used flexibly

Summary

In the above article, I have shown two ways to answer the question how to compare a string with an Enum in Python? Each method will have a different application audience. However, you can also use an operator. Please read and practice carefully to make a decision. Thanks for reading.

Maybe you are interested:

Leave a Reply

Your email address will not be published. Required fields are marked *