文字列が空かどうかをチェックする Python プログラム
Python 文字列は不変であり、その操作を議論する際の処理がより複雑になります。スペースを含む文字列は実際には空の文字列ですが、サイズがゼロではないことに注意してください。この記事では、その問題とその解決策についても説明しました。さまざまな方法を見てみましょう 文字列が空かどうかを確認する パイソン 。
例
Input: [' '] Output: Yes Explanation: In this, We are checking if the string is empty or not.
Pythonで空の文字列をチェックする
Python で文字列が空かどうかを確認するさまざまな方法を次に示します。
- len() の使用
- not() の使用
- not + str.strip() を使用する
- not + str.isspace の使用
- リスト内包表記の使用
- ブール値の使用
- ストリップメソッドの使用
- および Operator +strip() 関数の使用
- all() 関数の使用
- try/excel の使用
Python Len() を使用して空の文字列をチェックする
使用する のみ() これは、長さがゼロの文字列をチェックする最も一般的な方法です。ただし、スペースだけの文字列は、ゼロ以外であっても実際には空の文字列と見なされるべきであるという事実は無視されます。
Python3
# initializing string> test_str1> => ''> test_str2> => ' '> # checking if string is empty> print> (> 'The zero length string without spaces is empty ? : '> , end> => '')> if> (> len> (test_str1)> => => 0> ):> > print> (> 'Yes'> )> else> :> > print> (> 'No'> )> # prints No> print> (> 'The zero length string with just spaces is empty ? : '> , end> => '')> if> (> len> (test_str2)> => => 0> ):> > print> (> 'Yes'> )> else> :> > print> (> 'No'> )> |
出力
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No
Python チェック文字列が空です Not() を使用する
not 演算子も len() と同様のタスクを実行し、長さ 0 の文字列をチェックしますが、上記と同様に、スペースだけの文字列も空ではないとみなしますが、実際にはそうではありません。
Python3
# initializing string> test_str1> => ''> test_str2> => ' '> # checking if string is empty> print> (> 'The zero length string without spaces is empty ? : '> , end> => '')> if> (> not> test_str1):> > print> (> 'Yes'> )> else> :> > print> (> 'No'> )> # prints No> print> (> 'The zero length string with just spaces is empty ? : '> , end> => '')> if> (> not> test_str2):> > print> (> 'Yes'> )> else> :> > print> (> 'No'> )> |
出力
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No
Python の空の文字列 で 歌わない + str.strip()
空 + 長さゼロの文字列の問題は、strip() を使用することで解決できる可能性があります。strip() はスペースに遭遇すると true を返すため、スペースをチェックすることで、純粋に空の文字列をチェックする問題を解決できます。
Python3
# initializing string> test_str1> => ''> test_str2> => ' '> # checking if string is empty> print> (> 'The zero length string without spaces is empty ? : '> , end> => '')> if> (> not> (test_str1> and> test_str1.strip())):> > print> (> 'Yes'> )> else> :> > print> (> 'No'> )> # prints Yes> print> (> 'The zero length string with just spaces is empty ? : '> , end> => '')> if> (> not> (test_str2> and> test_str2.strip())):> > print> (> 'Yes'> )> else> :> > print> (> 'No'> )> |
出力
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes
空の文字列をチェックする Python u 歌わない + str.isspace
上記のメソッドと同様に機能し、文字列内のスペースをチェックします。このメソッドは、strip() がストリップ操作を実行する必要があるため、より効率的です。ストリップ操作が必要ない場合は、この操作にも計算負荷がかかります。スペースの数は十分です。
Python3
# initializing string> test_str1> => ''> test_str2> => ' '> # checking if string is empty> print> (> 'The zero length string without spaces is empty ? : '> , end> => '')> if> (> not> (test_str1> and> not> test_str1.isspace())):> > print> (> 'Yes'> )> else> :> > print> (> 'No'> )> # prints Yes> print> (> 'The zero length string with just spaces is empty ? : '> , end> => '')> if> (> not> (test_str2> and> not> test_str2.isspace())):> > print> (> 'Yes'> )> else> :> > print> (> 'No'> )> |
出力
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes
リスト内包表記を使用して文字列が空かどうかを確認する
このアプローチでは、リスト内包表記を使用してテキストを文字のリストに解析し、リストが空かどうかを判断する必要があります。リストの真実性を評価することで、文字列が空かどうかを評価できます。
Python3
string> => ''> x> => [> 'no'> if> len> (string)>>> 0> else> 'yes'> ]> print> (x)> |
出力
['yes']
Python の空文字列か Bool を使用していないことを確認する
1 つのアプローチは、 ブール関数 。 bool 関数は、空の文字列の場合は False を返し、空でない文字列の場合は True を返します。以下は、bool 関数を使用して文字列が空かどうかを確認する例です。
Python3
# Initializing a string> test_str> => ''> # Checking if the string is empty> if> not> bool> (test_str):> > print> (> 'The string is empty.'> )> else> :> > print> (> 'The string is not empty.'> )> #This code is contributed by Edula Vinay Kumar Reddy> |
出力
The string is empty.
また、ブール関数を使用して、strip メソッドを使用して先頭または末尾の空白を削除した後、文字列が空かどうかを確認することもできます。
Python3
# Initializing a string> test_str> => ' '> # Checking if the string is empty after removing leading and trailing whitespaces> if> not> bool> (test_str.strip()):> > print> (> 'The string is empty.'> )> else> :> > print> (> 'The string is not empty.'> )> #This code is contributed by Edula Vinay Kumar Reddy> |
出力
The string is empty.
Python 文字列チェック Strip メソッドを使用すると空になります
ここではPythonを使用します ストリップ() メソッド 文字列が空かどうかを確認します。
Python3
#input empty with and without spaces string> s> => ''> str> => ' '> > if> s.strip():> > print> (f> 'string, string1 = '{s}', with no spaces is not empty'> )> else> :> > print> (f> 'string, string1 = '{s}', with no spaces is empty'> )> > if> str> .strip():> > print> (f> 'string, string2 = '{str}', with spaces is not empty'> )> else> :> > print> (f> 'string, string2 = '{str}', with spaces is empty'> )> |
出力
string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty
文字列が空であるかどうかをチェックし、演算子+strip()関数を使用していないことを確認します
このアプローチでは、and 演算子を使用して、文字列が None でないかどうかを判断することと、文字列のストリップされたバージョンが空であるかどうかを判断する 2 つのテストを組み合わせることができます。先頭と末尾の空白文字は、strip() 関数によって文字列から削除されます。
Python3
#input empty with and without spaces string> string1> => ''> string2> => ' '> > if> string1> and> string1.strip():> > print> (f> 'string, string1 = '{string1}', with no spaces is not empty'> )> else> :> > print> (f> 'string, string1 = '{string1}', with no spaces is empty'> )> > if> string2> and> string2.strip():> > print> (f> 'string, string2 = '{string2}', with spaces is not empty'> )> else> :> > print> (f> 'string, string2 = '{string2}', with spaces is empty'> )> |
出力
string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty
Python 文字列チェック all() 関数を使用すると空です
all() 関数の戻り値には、入力として Iterable が必要です。 Iterable が空であるか、そのメンバーがすべて true の場合、値は true です。 all() 関数は、文字列を反復可能な文字として受け取ることで、文字列が空かどうか、またはその文字がすべて false (空の文字列) かどうかを判断できます。
Python3
string> => ''> if> all> (char.isspace()> for> char> in> string):> > print> (> 'The string is empty'> )> else> :> > print> (> 'The string is not empty'> )> |
出力
The string is empty
文字列が空かどうかをチェックするための bool アプローチには、 時間の複雑さ これは単に文字列の真理値をチェックするだけであり、定数時間の操作であるためです。の 補助スペース i ■ 文字列の真理値を格納するのに 1 つのブール変数だけが必要なため、O(1) ともなります。
Python Try/Exceptを使用して空の文字列をチェックする
Try-Except ブロックを使用すると、Python で文字列が空かどうかを判断できます。 try-excel ブロックを使用すると、コードの実行中に発生する可能性のある特定の例外をキャッチして処理できます。 Try-Except ブロックを使用すると、空の文字列をチェックするときなど、エラーの可能性が予想される場合に状況を適切に管理できます。
Python3
# Initialize an empty string> string> => ''> try> :> > # Try to access the first character of the string> > string[> 0> ]> > # If no exception is raised, print 'The string is not empty.'> > print> (> 'The string is not empty.'> )> except> :> > # If a ValueError exception is raised, print 'The string is empty.'> > print> (> 'The string is empty.'> )> |
出力
The string is empty
複雑さの分析:
このコードは、文字列の最初の文字へのアクセスのみを試行するため、一定の時間計算量は O(1) であり、文字列の長さに関係なく同じ時間がかかります。