简体   繁体   English

“是”不在python IDE中工作,而是在命令行中工作

[英]“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 : 看看这个python代码:

    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. 所以,当我在PyScripter IDE中编写它时,它既不显示错误也不显示输出。 But I tried the same code in python shell, its working! 但我在python shell中尝试了相同的代码,它的工作原理!

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. is关键字仅在字符串具有完全相同的标识时才起作用,即使字符串具有相同的值,也不能保证。 You should use == instead of is here to compare the values of the strings. 您应该使用==代替的is这里比较字符串的值。

Or better still, use endswith : 或者更好的是,使用endswith

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

You should use == in this case instead of is . 你应该使用==在这种情况下,而不是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. Is对象的标识进行检查,即id('e')必须与切片返回的字符串的id相等。 As it happens, cpython stores one-letter strings (and small integers) as constants so this often works. 碰巧,cpython将单字母字符串(和小整数)存储为常量,因此这通常有效。 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. 但它不可靠,因为任何其他实现都不能使用它,然后即使"e" is "e"也不必产生​​True。 Just use == and it should work. 只需使用== ,它应该工作。

edit: endswith mentioned by @MarkByers is even better for this case. 编辑: endswith提到的endwith在这种情况下更好。 safer, more readable and all that 更安全,更具可读性

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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