-1

Why is a string with a minus sign not recognised properly when passed to a function in python? The simple code

def f(s):
    print(s)
    if s is 'a-b':
        print('I expect this to be printed.')
    else:
        print('Instead, this is printed.')


s = 'a-b'
if s is 'a-b':
    print('Oustide everything is fine.')
f(s)

gives the output

Oustide everything is fine.
a-b
Instead, this is printed.

Can someone explain please why this happens? Without the minus sign everything is fine.

Alehud
  • 106
  • 9
  • 5
    `is` is not how you do an equality test. – user2357112 Nov 15 '20 at 23:27
  • I disagree with the downvotes here, btw. There isn't enough context for someone unfamiliar with programming to know "what to Google" to downvote this. All we see here is someone doing something reasonable and getting an unexpected answer from the language. – kojiro Nov 15 '20 at 23:34
  • Thanks for explaining! Part of my confusion was because for a string without the minus sign everything worked as expected. So, I thought it has something to do with the minus sign. – Alehud Nov 15 '20 at 23:43
  • @Alehud if you can, take the time to read through the [Python Data Model](https://docs.python.org/3/reference/datamodel.html). Even if it doesn't all make sense, it can give you an idea where to look when things don't work as expected, and it can help you figure out what to Google next. – kojiro Nov 15 '20 at 23:45

1 Answers1

2

Python distinguishes between values that are equal and values that are identical. You should use the is operator rarely. In fact, you probably won't encounter too many cases where you use is other than is None.

Here, you want if s == 'a-b':.

kojiro
  • 74,557
  • 19
  • 143
  • 201