简体   繁体   中英

“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.

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"

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM