在python中传递给函数的带减号的字符串
为什么在python中传递给函数时带负号的字符串不能正确识别?简单代码在python中传递给函数的带减号的字符串,python,string,Python,String,为什么在python中传递给函数时带负号的字符串不能正确识别?简单代码 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)
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)
给出输出
Oustide everything is fine.
a-b
Instead, this is printed.
有人能解释一下为什么会这样吗?没有减号,一切正常。Python区分相等的值和相同的值。您应该很少使用
is
操作符。事实上,您可能不会遇到太多使用is
而不是is None
的情况
这里,你想要
如果s=='a-b':
不是你做平等测试的方式。顺便说一句,我不同意这里的否决票。没有足够的上下文让不熟悉编程的人知道“谷歌做什么”来否决这个。我们在这里看到的只是某人做了一些合理的事情,并从语言中得到了意想不到的答案。感谢您的解释!我的困惑部分是因为对于一个没有负号的字符串,一切都按预期进行。所以,我认为这与负号有关。@Alehud如果可以的话,花点时间通读一下。即使这一切都没有意义,它也能让你知道当事情不按预期运行时应该去哪里寻找,并能帮助你找出下一步该怎么做。