Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

String match is not working in python

Tags:

python

string

here is my Django code

print request.user.role
print request.user.role is "Super"
print request.user.role == "Super"
print "Super" is "Super"

and the output on console is

Super
False
False
False
True

I am wondering why it is not matching the exact string

like image 538
Muhammad Usman Avatar asked Sep 23 '26 20:09

Muhammad Usman


2 Answers

It is because request.user.role is not a string. As a result, comparing it with a string "Super" will return false, as there is no implicit type comparison. You must convert it to a string if you want to compare it to one. To convert to a string, you can try this:

str(request.user.role)

Your last print returns true because you are just comparing the string "Super" to itself, evidently. Also as a side note, you only want to use is when comparing identities, not values.

like image 120
HavelTheGreat Avatar answered Sep 26 '26 09:09

HavelTheGreat


Please do not use string comparison to check for user roles. This approach is error prone, may use more memory for new created strings and is dangerous overall. For example if value that represents role is not it's name you will have to keep track of name-value mapping yourself. Or if library will change it's mind and swap names to integers etc.

All libraries that provide such functionality has roles enum lying somewhere with all the values for roles. So, for example, in django-user-roles you can do

user.role.is_super # maybe role.is_Super
# or
from userroles import roles
user.role == roles.super # maybe roles.Super

This is much more readable and safer aproach.

like image 24
pss Avatar answered Sep 26 '26 08:09

pss



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!