2

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.

user1027046
  • 293
  • 1
  • 6
  • 11
  • 1
    Have you tried just having the script repeat the input to see what comes in when using the IDE and the shell? – Björn Pollex Nov 14 '11 at 15:30
  • 2
    Related: http://stackoverflow.com/questions/26595/is-there-any-difference-between-foo-is-none-and-foo-none. `is` is the wrong operator here -- use `==` instead. – Sven Marnach Nov 14 '11 at 15:31
  • 2
    A couple of things .. 1. Are you *sure* it's working like that anywhere? It shouldn't. `is` is the identity operator and two strings with the same value are not identical, they are equal so you should be using `==`, also 2, Note you can use negative indexes in sequences so, you do not need to know the length of `word` you can just use `word[-1]` to get the last character. – tjm Nov 14 '11 at 15:33
  • @tjm: It is perfectly possible that this works due to string interning or similar things. Strings are immutable, so the interpreter is free to reuse them where appropriate, – Sven Marnach Nov 14 '11 at 15:41
  • @SvenMarnach. Ah ok. Good to know. I guess I've got a little reading to do myself then. And to the OP, let me rephrase that then, not as it *shouldn't* work, but it is not *guaranteed* to work. – tjm Nov 14 '11 at 15:47

2 Answers2

9

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"
Mark Byers
  • 811,555
  • 193
  • 1,581
  • 1,452
6

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

rplnt
  • 2,341
  • 16
  • 14