在 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 许可协议
空字符串被认为是错误的。