0

For some reason when I try to make a string lowercase and check for equality with the 'is' operator, it returns false.

I have tried converting the strings to ascii tuples and found that they still have the exact same numbers, and are the exact same type, but they still fail the test.

'HELLO'.lower() is 'hello'  # False
'hello' is 'hello'  # True

'HELLO'.lower()  # 'hello'
x = 'HELLO'.lower()
x  # 'hello'
x is 'hello'  # False

tuple(map(lambda x: ord(x), 'hello'))  # (104, 101, 108, 108, 111)
tuple(map(lambda x: ord(x), 'HELLO'.lower()))  # (104, 101, 108, 108, 111)

tuple(map(lambda x: ord(x), 'hello')) is tuple(map(lambda x: ord(x), 'HELLO'.lower()))  # False

Should these strings not be equal?

jonrsharpe
  • 115,751
  • 26
  • 228
  • 437
BryceTheGrand
  • 643
  • 3
  • 9

2 Answers2

2

If you want to check that the values of two objects are the same, you should use the == operator instead.

The is operator verifies that two operands refer to the same object.

Some examples that better illustrate the differences between these two operators can be found here.

1

The 2 objects 'HELLO'.lower() and 'hello' do not have the same string associated with them, is compares objects

'HELLO' is the string in the first object & you are appying the method .lower() to it. The second object's string is 'hello'. Hence the 2 objects are different

Try,

'HELLO'.lower() == 'hello'

This will compare the string from object 1 when converted to lower case & not the object itself.

DrBwts
  • 3,470
  • 6
  • 38
  • 62