logo

Program Python na kontrolu, či je reťazec prázdny alebo nie

Reťazce Pythonu sú nemenné a pri diskusii o ich operáciách sa s nimi zaobchádza zložitejšie. Všimnite si, že reťazec s medzerami je v skutočnosti prázdny reťazec, ale má nenulovú veľkosť. Tento článok tiež diskutoval o tomto probléme a jeho riešení. Pozrime sa na rôzne metódy Skontrolujte, či je reťazec prázdny Python .

Príklad

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

Skontrolujte prázdny reťazec v Pythone

Tu sú rôzne spôsoby, ako skontrolovať, či je reťazec prázdny alebo nie v Pythone.



  • Použitie len()
  • Použitie not()
  • Použitie not + str.strip()
  • Použitie not + str.isspace
  • Používanie porozumenia zoznamu
  • Pomocou Bool
  • Použitie pásových metód
  • Používanie a Operátor + funkcia strip().
  • Pomocou funkcie all().
  • Pomocou try/okrem

Python Check String Empty pomocou Len()

Použitím len() je najvšeobecnejšia metóda na kontrolu reťazcov s nulovou dĺžkou. Aj keď ignoruje skutočnosť, že reťazec s iba medzerami by sa mal prakticky považovať za prázdny reťazec, aj keď 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 konštanty
>

>

Výkon

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

Kontrolný reťazec Python je prázdny pomocou Not()

Operátor not môže tiež vykonávať úlohu podobnú len() a kontroluje reťazec dĺžky 0, ale rovnako ako vyššie uvedené považuje aj reťazec len s medzerami za neprázdny, čo by v praxi nemalo byť 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ýkon

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

Prázdny reťazec Pythonu v nespievaj + str.strip()

Problém prázdneho reťazca + nulovej dĺžky možno odstrániť použitím strip(), strip() vráti true, ak narazí na medzery, takže jeho kontrola môže vyriešiť problém kontroly čisto prázdneho reťazca.

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ýkon

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

Začiarknite políčko Empty String Python u spievať nie + str.isspace

Funguje podobným spôsobom ako vyššie uvedená metóda a kontroluje medzery v reťazci. Táto metóda je efektívnejšia, pretože strip() vyžaduje vykonať aj operáciu strip, ktorá si vyžaduje výpočtové zaťaženie, ak nie. miest 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ýkon

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

Skontrolujte, či je reťazec prázdny alebo či nie pomocou funkcie List Comprehension

Tento prístup znamená analyzovať text do zoznamu znakov pomocou porozumenia zoznamu a potom určiť, či je zoznam prázdny. Či je reťazec prázdny alebo nie, môžeme posúdiť posúdením pravdivosti zoznamu.

Python3




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

>

>

Výkon

['yes']>

Začiarknite políčko Prázdny reťazec Pythonu alebo nepoužívanie Bool

Jedným z prístupov je použitie boolova funkcia . Funkcia bool vracia hodnotu False pre prázdne reťazce a True pre neprázdne reťazce. Tu je príklad použitia funkcie bool na kontrolu, či je reťazec prázdny alebo nie.

Python3




ako zakázať režim vývojára
# 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ýkon

The string is empty.>

Môžete tiež použiť funkciu bool na kontrolu, či je reťazec prázdny alebo nie po odstránení akýchkoľvek úvodných alebo koncových medzier pomocou metódy 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ýkon

The string is empty.>

Python Skontrolujte, či je reťazec je prázdny použitím Strip Method

Tu budeme používať Python strip() metódy aby ste skontrolovali, či je reťazec prázdny alebo nie.

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ýkon

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

Skontrolujte, či je reťazec prázdny alebo sa nepoužíva a operátor + funkcia strip().

V tomto prístupe sa operátor and používa na kombináciu dvoch testov: určenie, či reťazec nie je None, a určenie, či je zbavená verzia reťazca prázdna. Počiatočné a koncové medzery sú z reťazca odstránené funkciou 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ýkon

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

Python Skontrolujte, či je reťazec je prázdne Použitie funkcie all().

Návratová hodnota funkcie all() vyžaduje Iterable ako vstup. Ak je Iterable prázdny alebo všetky jeho členy sú pravdivé, hodnota je true. Funkcia all() môže určiť, či je reťazec prázdny, alebo či sú všetky jeho znaky nepravdivé (prázdny reťazec) prijatím reťazca ako opakovateľného znaku.

Python3




konverzia reťazca java na celé číslo

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

>

>

Výkon

The string is empty>

Boolov prístup na kontrolu, či je reťazec prázdny alebo nie, má a časová zložitosť z O(1), pretože jednoducho kontroluje pravdivostnú hodnotu reťazca, čo je operácia s konštantným časom. The Pomocný priestor i s tiež O(1), pretože vyžaduje iba jednu boolovskú premennú na uloženie pravdivostnej hodnoty reťazca.

Python skontrolujte prázdny reťazec pomocou Try/Except

Pomocou bloku try-except môžete v Pythone určiť, či je reťazec prázdny. Pomocou bloku try-except môžete zachytiť a vysporiadať sa s konkrétnymi výnimkami, ktoré by mohli vzniknúť počas vykonávania vášho kódu. Môžete elegantne zvládnuť okolnosti, keď očakávate pravdepodobnú chybu, napríklad keď skontrolujete prázdny reťazec, pomocou 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ýkon

The string is empty>

Analýza zložitosti:
Tento kód má konštantnú časovú zložitosť O(1), pretože sa pokúša získať prístup len k prvému znaku reťazca, čo trvá rovnako dlho bez ohľadu na dĺžku reťazca.