3

The code below depicts two cases, which compare identical strings. Why do they yield different results, even though both have strings which are identical within each case?

Case 1:

a = 'hello'
b = 'hello'
a is b
True

Case 2:

a = 'hello!'
b = 'hello!'
a is b
False

I was not able to find a reason as to why '!' would make a difference in a variable's truth value.

Mazdak
  • 105,000
  • 18
  • 159
  • 188
arkadiy
  • 746
  • 1
  • 10
  • 26
  • 1
    Not sure these get at what's going on. I've noticed this before. Strings with only alphanumeric characters will return `True` for `a is b`, but once you throw in a special character, it becomes `False`. Never figured it out unfortunately! – busybear Dec 14 '18 at 22:12
  • 3
    @busybear because strings that are valid identifiers/names get *interned*. – jonrsharpe Dec 14 '18 at 22:13
  • @jonrsharpe Why is it relevant whether the string looks like an identifier in the language, when choosing whether to use [string interning](https://en.wikipedia.org/wiki/String_interning) with it or not? – Jeppe Stig Nielsen Dec 14 '18 at 22:17
  • 1
    @JeppeStigNielsen because the interpreter interns identifiers. Anyway, here's some more info: https://stackoverflow.com/questions/35805768/what-are-the-rules-for-cpythons-string-interning – juanpa.arrivillaga Dec 14 '18 at 22:32

0 Answers0