0

My understanding is that the "is" keyword checks that two objects are in fact the same object.

str types are immutable and can be compared using "is" as (I'm assuming) they are always represented by the same underlying object. e.g.

"abc" is "abc" # True
a = "abc"; a == "abc" # True
lst = ["abc", 1, 2]; lst[0] is "abc" # True

However (arbitrary examples I know), If i did something like this:

string_a = "abc_123"
string_b = re.search("abc", string_a).group() # gets "abc"
cls = type(string_b). # Says its a str type
string_b == "abc"  # Returns True & Shows me that it is "abc"
string_b is "abc"  # Returns False.

Why does the last line return False when string_b is of type str and equals "abc"?

Alesi Rowland
  • 379
  • 2
  • 16
  • 5
    Does this answer your question? [Python string interning](https://stackoverflow.com/questions/15541404/python-string-interning) – tzaman Jun 29 '20 at 16:23
  • 1
    Immutability and interning are quite separate things, see the linked dupe for some discussion. – tzaman Jun 29 '20 at 16:23
  • I'm pretty sure it's because one of them is a variable and one is a string. Though they are the same object (which you can check with `type(string_b) is type("abc")`), they are not the exact same *thing*. **I dunno** – theX Jun 29 '20 at 16:46
  • Think tzaman has the right answer – Alesi Rowland Jun 29 '20 at 17:16

0 Answers0