def myFunc( str ):
      print "str=", str
      if str == None:
        print "str is None"
      else:
        print "str is not None, value is:", str

此功能在我的应用程序中多次称为str,none none。但是,有时,尽管str没有,但测试失败并打印出来:

str=None
str is not None, value is None

怎么会发生?

有帮助吗?

解决方案

字符串 'None' 和bytestring b'None' 两者都不会打印出来,但实际上并非没有。另外,您可以拥有自定义课程来覆盖他们的 __str__ 返回的方法 'None', ,尽管实际上不是没有。

一些美学注释:Python保证只有一个实例 None, ,所以你应该使用 is 代替 ==. 。另外,您不应命名您的变量 str, ,因为那是内置的名称。

尝试此定义:

def myFunc(s):
    if s is None:
        print('str is None')
    else:
        print('str is not None, it is %r of type %s' % (s, type(s).__name__))

其他提示

检查价值 str 再次。如果您的测试失败,则 str 不是特别 None 目的。大概str实际上是弦 'None'.

>>> str = None
>>> str == None
True
>>> str = 'None'
>>> str == None
False
>>> print str
None

从您的评论来判断 str 实际上是 u'None' 这是一串类型 unicode. 。您可以这样测试:

>>> s = unicode('None')
>>> s
u'None'
>>> print s
None
>>> s == 'None'
True

现在,尽管您可以做到这一点,但我怀疑您的问题在其他地方。调用代码必须将此对象转换为字符串,例如 unicode(None). 。如果对象不是 None.

有可能 str 被绑定到字符串对象 "None" 在任何情况下?

我建议使用 if str is None 代替 ==. 。更不用说,您真的不应该使用 str 作为变量名称。

您也可以使用 __repr__ 显示值的方法:

>>> x = None
>>> print 'the value of x is', x.__repr__()
the value of x is None
>>> x = "None"
>>> print 'the value of x is', x.__repr__()
the value of x is 'None'
许可以下: CC-BY-SA归因
不隶属于 StackOverflow
scroll top