如何用 Pythonic 的方式来检查字符串是否为空
Jinku Hu
2020年6月25日
2018年3月6日
Python 中我们有好几种方式来检查某字符串是否为空,比如,
>>> A = ""
>>> A == ""
True
>>> A is ""
True
>>> not A
True
最后的方法 not A
是最 Pythonic 的方式,它是由 Python PEP8来推荐使用的。默认的,空序列和数据集合都等同于布尔数值中的 False
。
我们推荐 not A
这种方式因为它不仅是最 Pythonic,而且它也是效率最高的。可以参考下面的运行时间比较。
>>> timeit.timeit('A == ""', setup='A=""',number=10000000)
0.4620500060611903
>>> timeit.timeit('A is ""', setup='A=""',number=10000000)
0.36170379760869764
>>> timeit.timeit('not A', setup='A=""',number=10000000)
0.3231199442780053
Author: Jinku Hu
Founder of DelftStack.com. Jinku has worked in the robotics and automotive industries for over 8 years. He sharpened his coding skills when he needed to do the automatic testing, data collection from remote servers and report creation from the endurance test. He is from an electrical/electronics engineering background but has expanded his interest to embedded electronics, embedded programming and front-/back-end programming.
LinkedIn