如何用 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