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

在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""对我来说有点太难编码了。但是,如果那是最好的方法,那就去吧。 🙂 谢谢你尽你所能的帮助。

参考方案

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

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

Python uuid4,如何限制唯一字符的长度 - python

在Python中,我正在使用uuid4()方法创建唯一的字符集。但是我找不到将其限制为10或8个字符的方法。有什么办法吗?uuid4()ffc69c1b-9d87-4c19-8dac-c09ca857e3fc谢谢。 参考方案 尝试:x = uuid4() str(x)[:8] 输出:"ffc69c1b" Is there a way to…

符合当今标准的Python字符串格式 - python

我正在从我2017年购买的书和在线课程中同时学习python。这本书说我应该像这个例子那样格式化字符串。print("Guess number %d of %d" % (variable1, variable2)) 但是在线课程说我应该这样格式化;print("Guess number {} of {}".format…

Python 3会流行吗? - python

我已经学习了一些Python 2和Python 3,似乎Python 2总体上比Python 3更好。这就是我的问题所在。是否有充分的理由真正切换到python 3? 参考方案 总体上,甚至在大多数细节上,Python3都比Python2更好。关于第三方库, Python 3落后于的唯一区域是。使Python变得如此出色的原因不仅在于它作为一种语言的内在特性…

Python-如何检查Redis服务器是否可用 - python

我正在开发用于访问Redis Server的Python服务(类)。我想知道如何检查Redis Server是否正在运行。而且如果某种原因我无法连接到它。这是我的代码的一部分import redis rs = redis.Redis("localhost") print rs 它打印以下内容<redis.client.Redis o…

字符串文字中的正斜杠表现异常 - python

为什么S1和S2在撇号位置方面表现不同?S1="1/282/03/10" S2="4/107/03/10" R1="".join({"N\'" ,S1,"\'" }) R2="".join({"N\'…