在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."
相反,我必须这样写,让它为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."
…像这样让它对non-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""
有点太硬了。但如果这是最好的方法,那就这样吧。:)谢谢你的帮助
空字符串被认为是假的。
if string:
# String is not empty.
else:
# String is empty.
您永远不要想要使用is
与任何不能保证是单例的。检查返回值的长度,如果它是unicode
的实例
我不得不质疑你的第一个陈述;
# Works for normal empty strings <-- WRONG
if string is not None:
print "string is not an empty string."
在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
Check what ?
if s is None:
print "s is None"
else:
if isinstance(s, unicode):
print "s is unicode, %r" % s
else:
print "s is bytes, %r" % s
if s:
print "s is not empty"
else:
print "s is empty"
像往常一样先检查None
None
当然是在对话中包含的一个好东西,特别是如果您正在编写一个可以被其他程序员使用的类。
None
是一个合法的、完全唯一的值。
我是新的 Python,所以我还没有完全精通None
的'正确的'用法。最常用于字符串和列表的初始化。如果我的代码遇到这样的情况,我试图对字符串或列表做一些事情,而我的代码没有特别设置一个值,我想知道它。我把它当作某种安全网。
if my_string is '': print('My string is NULL')
elif my_string is None : print('My string.... isn't')
else: print('My string is ' + my_string)
# Python3.8
string = ' '
if string:
print("Hello World from first statement")
#this will be print the above line
if string and string.strip():
print('This will not print anything')
string = None
if string:
print("will not print anything")
string = ''
if string:
print("still will not print anything")
first_string = ' '
second_string = ''
if first_string and second_string:
print('will not print anything')