user1027046
user1027046

Reputation: 293

"is" not working in python IDE but working in command line

I couldn't understand why this is happening actually..

Take a look at this python code :

    word = raw_input("Enter Word")
    length = len(word)

    if word[length-1:] is "e" :
         print word + "d"

If I give input "love", its output must be "loved". So, when I wrote this in PyScripter IDE, its neither showing error nor the output. But I tried the same code in python shell, its working!

I'd like to know why this is happening.

Upvotes: 2

Views: 203

Answers (2)

rplnt
rplnt

Reputation: 2409

You should use == in this case instead of is. Is checks for identity of objects, that is, id('e') would have to be equal with id of the string returned by the slice. As it happens, cpython stores one-letter strings (and small integers) as constants so this often works. But it is not reliable as any other implementation could not use this and then even "e" is "e" wouldn't have to yield True. Just use == and it should work.

edit: endswith mentioned by @MarkByers is even better for this case. safer, more readable and all that

Upvotes: 6

Mark Byers
Mark Byers

Reputation: 838066

The is keyword will only work if the strings have exactly the same identity, which is not guaranteed even if the strings have the same value. You should use == instead of is here to compare the values of the strings.

Or better still, use endswith:

if word.endswith("e"):
     print word + "d"

Upvotes: 9

Related Questions