Aditya Aditya - 1 month ago 9
Python Question

python- string equality and ord() comparison?

s1 = request.args.get('s1', '')
s2 = request.args.get('s2', '')

if '' not in [s1, s2]:
if s1 == s2:
if all(ord(c1) is ord(c2) for c1, c2 in zip(s1, s2)):
msg = "first"
else:
msg += "second"
else:
msg = "thrid"
else:
msg = 'fourth'


I want this piece of code to print "second".

I tried these inputs
s1 = ".0" and s2 = "0.00"

Could anyone please explain in brief what "
if all(ord(c1) is ord(c2) for c1, c2 in zip(s1, s2)):
" means exactly?

Thanks in advance for any help.

PS : Please excuse the indentation. Python beginner here!

Answer

There's no 100% sure way of making that piece of code print second, since interning is an implementation detail.

CPython interns integers in the [-5, 256] range,

So you'll need a character that when it's passed to ord returns something > 256.

>>> s1 = "asdሴ"
>>> s2 = "asdሴ"
>>> s1 == s2
True
>>> all(ord(c1) is ord(c2) for c1, c2 in zip(s1, s2))
False

all(ord(c1) is ord(c2) for c1, c2 in zip(s1, s2)) checks if every ord(c1) has the same id as ord(c2).

From the id documentation:

Return the “identity” of an object. This is an integer which is guaranteed to be unique and constant for this object during its lifetime. Two objects with non-overlapping lifetimes may have the same id() value.

CPython implementation detail: This is the address of the object in memory.

Comments