logo

Program Python pro kontrolu, zda je řetězec prázdný nebo ne

Řetězce Pythonu jsou neměnné a při projednávání jejich operací se s nimi pracuje složitější. Všimněte si, že řetězec s mezerami je ve skutečnosti prázdný řetězec, ale má nenulovou velikost. Tento článek také pojednával o tomto problému a jeho řešení. Podívejme se na různé metody Zkontrolujte, zda je řetězec prázdný Krajta .

Příklad



  Input:  [' ']   Output:   Yes   Explanation:   In this, We are checking if the string is empty or not.>

Zkontrolujte prázdný řetězec v Pythonu

Zde jsou různé metody, jak zkontrolovat, zda je řetězec prázdný nebo ne v Pythonu.

  • Použití len()
  • Použití not()
  • Použití not + str.strip()
  • Použití not + str.isspace
  • Použití porozumění seznamu
  • Pomocí Bool
  • Použití pásových metod
  • Použití a Operátor + funkce strip().
  • Použití funkce all().
  • Pomocí try/except

Python Check String Empty pomocí Len()

Použitím jen() je nejobecnější metodou pro kontrolu řetězců nulové délky. I když ignoruje skutečnost, že řetězec pouze s mezerami by měl být prakticky považován za prázdný řetězec, i když je nenulový.

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'>)>

java n-tice
>

>

Výstup

The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No>

Kontrolní řetězec Python je prázdný pomocí Not()

Operátor not může také provádět úlohu podobnou len() a kontroluje řetězec délky 0, ale stejně jako výše považuje řetězec pouze s mezerami za neprázdný, což by prakticky neměla být pravda.

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'>)>

>

>

Výstup

The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No>

Prázdný řetězec Pythonu v nezpívej + str.strip()

Problém prázdného řetězce + nulové délky lze odstranit použitím strip(), strip() vrátí true, pokud narazí na mezery, takže jeho kontrola může vyřešit problém kontroly čistě prázdného řetězce.

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'>)>

>

>

Výstup

The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes>

Zaškrtněte políčko Empty String Python u zpívat ne + str.isspace

Funguje podobným způsobem jako výše uvedená metoda a kontroluje mezery v řetězci. Tato metoda je efektivnější, protože strip() vyžaduje také provedení operace strip, která zabere výpočetní zatížení, pokud ne. míst je dobrý počet.

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'>)>

>

>

Výstup

The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes>

Zkontrolujte, zda je řetězec prázdný nebo zda nepoužívá funkci List Comprehension

Tento přístup zahrnuje analýzu textu do seznamu znaků pomocí porozumění seznamu a poté určení, zda je seznam prázdný. Zda je řetězec prázdný či nikoli, můžeme vyhodnotit posouzením pravdivosti seznamu.

Python3




string>=>''> x>=>[>'no'> if> len>(string)>>0> else> 'yes'>]> print>(x)>

>

>

Výstup

objektivní java
['yes']>

Zkontrolujte Python Empty String nebo Not using Bool

Jedním z přístupů je použití boolova funkce . Funkce bool vrací hodnotu False pro prázdné řetězce a True pro neprázdné řetězce. Zde je příklad použití funkce bool ke kontrole, zda je řetězec prázdný nebo ne.

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>

>

>

Výstup

The string is empty.>

Můžete také použít funkci bool ke kontrole, zda je řetězec prázdný nebo ne po odstranění jakýchkoli úvodních nebo koncových mezer pomocí metody 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>

>

>

Výstup

The string is empty.>

Python Zkontrolujte, zda String je prázdný pomocí Strip Method

Zde použijeme Python metody strip(). zkontrolovat, zda je řetězec prázdný nebo ne.

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'>)>

>

>

Výstup

string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty>

Zkontrolujte, zda je řetězec prázdný nebo se nepoužívá, a operátor + funkce strip().

V tomto přístupu se operátor and používá ke kombinaci dvou testů: určení, zda řetězec není None, a určení, zda je odstraněná verze řetězce prázdná. Úvodní a koncové prázdné znaky jsou z řetězce odstraněny funkcí 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'>)>

>

>

Výstup

string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty>

Python Zkontrolujte, zda String je prázdné Použití funkce all().

Návratová hodnota funkce all() vyžaduje jako vstup Iterable. Pokud je Iterable prázdný nebo všechny jeho členy jsou pravdivé, hodnota je true. Funkce all() může určit, zda je řetězec prázdný nebo zda jsou všechny jeho znaky nepravdivé (prázdný řetězec), tím, že řetězec přijme jako iterovatelný znak.

Python3




řetězec nahradit vše java

string>=> ''> if> all>(char.isspace()>for> char>in> string):> >print>(>'The string is empty'>)> else>:> >print>(>'The string is not empty'>)>

>

>

Výstup

The string is empty>

Boolův přístup pro kontrolu, zda je řetězec prázdný nebo ne, má a časovou složitost of O(1), protože jednoduše kontroluje pravdivostní hodnotu řetězce, což je operace s konstantním časem. The Pomocný prostor I s také O(1), protože vyžaduje pouze jednu booleovskou proměnnou k uložení pravdivostní hodnoty řetězce.

Python zkontroluje prázdný řetězec pomocí Try/Except

Pomocí bloku try-except můžete v Pythonu určit, zda je řetězec prázdný. Pomocí bloku try-except můžete zachytit a vypořádat se s konkrétními výjimkami, které by mohly nastat během provádění vašeho kódu. Okolnosti, kdy očekáváte pravděpodobnou chybu, například když kontrolujete prázdný řetězec, můžete elegantně zvládnout pomocí bloku 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.'>)>

>

>

Výstup

The string is empty>

Analýza složitosti:
Tento kód má konstantní časovou složitost O(1), protože se pokouší získat přístup pouze k prvnímu znaku řetězce, což trvá stejně dlouho bez ohledu na délku řetězce.