Pythonic 方式で文字列が空であることを確認する方法
Jinku Hu
2020年6月25日
2018年3月6日
Python
Python String

Python では、文字列が空の文字列であるかどうかを確認するさまざまな方法があります。お気に入り
>>> A = ""
>>> A == ""
True
>>> A is ""
True
>>> not A
True
最後のメソッド not A
は、PEP8 の Programming Recommendationsが推奨する Python の方法です。デフォルトでは、空のシーケンスとコレクションは、Boolean
コンテキストで 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