Pythonでnot演算子やlenやstripを使って文字列が空かどうかをチェックする方法

スポンサーリンク

タイトルがちょっと変に聞こえますが、springが空かどうかをlen()かnot演算子で単純に調べられると思うかもしれませんね。

しかし、ここで覚えておかなければならないのは、この演算子は文字列の中に文字としてスペースを入れ、空でない文字列として表示してしまうということです。

この記事では、文字列が空かどうかを確認するために使用できるメソッドを学びます。

それでは、はじめましょう。

スポンサーリンク

Pythonで文字列が空かどうかを調べる方法

Pythonで文字列が空かどうかをチェックする4つの異なるメソッドを見てみましょう。

各メソッドを例題で探り、出力を示すことで、自分で同じことを実行できるようにします。

1. NOT演算子の使用

このメソッドは、スペースを含む文字列を空でない文字列と見なします。

文字列中の空白を1文字として数えます。

空白を含む文字列は空文字列であり、サイズが0でないことを知っておく必要がありますが、このメソッドはその事実を無視します。

例えば

str1 = ""
str2 = "  "
  
if(not str1):
    print ("Yes the string is empty")
else :
    print ("No the string is not empty")
  
if(not str2):
    print ("Yes the string is empty")
else :
    print ("No the string is not empty"

を結果を出力すると、以下の様になります。

Yes the string is empty
No the string is not empty

空白を含む文字列を空でない文字列として出力しているのがわかると思います。

2. len()関数の使用

not 演算子と同様に、これもスペースを含む文字列を空でない文字列とみなします。

この方法は、空でない長さ0の文字列があるかどうかを調べます。

例えば

str1 = ""
str2 = "  "
  
 
if(len(str1) == 0):
    print ("Yes the string is empty ")
else :
    print ("No the string is not empty")
  
 
if(len(str2) == 0):
    print ("Yes the strinf is empty")
else :
    print ("No the string is not empty")

結果は以下の通りです。

Yes the string is empty
No the string is not empty

3. not+str.strip() メソッドを使用します。

このメソッドは、空+ゼロ長でない文字列の事実を無視しない。

したがって、このメソッドは空のゼロ長文字列をチェックする目的を果たすことができます。

これは、空のゼロ長でない文字列を探します。

たとえば

str1 = ""
str2 = "  "
  
if(not (str1 and str1.strip())):
    print ("Yes the string is empty")
else :
    print ("No the string is not empty")
  
if(not(str2 and str2.strip())):
    print ("Yes the string is empty")
else :
    print ("No the string is not empty")

結果は、以下の通りです。

Yes the string is empty
Yes the string is empty

4. not str.isspace メソッドを使用する

このメソッドは上記のメソッドと似ている。

この方法は、文字列に多くのスペースが含まれる場合、計算負荷のかかるストリップ操作を行うため、より堅牢であると考えられる。

str1 = ""
str2 = "  "
  
 
if(not (str1 and not str1.isspace())):
    print ("Yes the string is empty")
else :
    print ("No the string is not empty")
  
 
if(not (str2 and not str2.isspace())):
    print ("Yes the string is empty")
else :
    print ("No the string is not empty")

結果を出力すると、以下の様になります。

Yes the string is empty
Yes the string is empty

まとめ

今回は、空文字列をチェックするためのさまざまな方法について学びました。

それぞれのメソッドには欠点もありますが、自分の適性に応じて使い分けるとよいでしょう。

タイトルとURLをコピーしました