在Python 2.7中,我正在编写一个类,该类调用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."
Run Code Online (Sandbox Code Playgroud)
相反,我必须像这样编写它以使其适用于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."
Run Code Online (Sandbox Code Playgroud)
...并且喜欢这样以使其在非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."
Run Code Online (Sandbox Code Playgroud)
第三种方法是最好的方法吗,还是有更好的方法?我问,因为写一个u""感觉有点太硬编码给我.但如果这是最好的方式,那就这样吧.:) 谢谢你尽你所能的帮助.
Art*_*par 47
空字符串被视为false.
if string:
# String is not empty.
else:
# String is empty.
Run Code Online (Sandbox Code Playgroud)
我必须挑战你的第一个声明;
# Works for normal empty strings <-- WRONG
if string is not None:
print "string is not an empty string."
Run Code Online (Sandbox Code Playgroud)
在Python 2.7.1中,"" is not None求值为True- 得到string=""结果string is not an empty string(当然是!).
为什么要None加入呢?
s = random_test_string()
s = API_call(s)
if len(s):
# string is not empty
pass
Run Code Online (Sandbox Code Playgroud)