在 Python 中对普通字符串和 Unicode 空字符串进行“not None”测试的最佳方法?

新手上路,请多包涵

在 Python 2.7 中,我正在编写一个调用 API 中的函数的类,该 API 可能返回也可能不返回空字符串。此外,空字符串可能是 unicode u"" 或非 unicode "" 。我想知道检查这个的最好方法是什么?

以下代码适用于空字符串,但不适用于空 unicode 字符串:

 class FooClass():
    string = ...
    string = might_return_normal_empty_string_or_unicode_empty_string(string)

    # Works for normal empty strings, not unicode:
    if string is not None:
        print "string is not an empty string."

相反,我必须像这样编写它才能使其适用于 unicode:

 class BarClass():
    string = ...
    string = might_return_normal_empty_string_or_unicode_empty_string(string)

    # Works for unicode empty strings, not normal:
    if string is not u"":
        print "string is not an empty string."

…并像这样让它适用于非 unicode 和 unicode 中的空字符串:

 class FooBarClass():
    string = ...
    string = might_return_normal_empty_string_or_unicode_empty_string(string)

    # Works for both normal and unicode empty strings:
    if string is not u"" or None:
        print "string is not an empty string."

第三种方法是最好的方法,还是有更好的方法?我问是因为写一个 u"" 对我来说感觉有点太硬编码了。但如果这是最好的方法,那就这样吧。 :) 谢谢你尽你所能的帮助。

原文由 Dave 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 606
2 个回答

空字符串被认为是错误的。

 if string:
    # String is not empty.
else:
    # String is empty.

原文由 Artur Gaspar 发布,翻译遵循 CC BY-SA 3.0 许可协议

永远 不想将 is 与任何不能保证是单例的东西一起使用。检查返回值的长度,以及它是否是 unicode 的实例。

原文由 Ignacio Vazquez-Abrams 发布,翻译遵循 CC BY-SA 3.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题