Program Python za preverjanje, ali je niz prazen ali ne
Nizi Python so nespremenljivi in imajo bolj zapleteno obravnavo, ko razpravljamo o svojih operacijah. Upoštevajte, da je niz s presledki pravzaprav prazen niz, vendar ima velikost, ki ni enaka nič. Ta članek je obravnaval tudi ta problem in rešitev zanj. Oglejmo si različne metode Preverite, ali je niz prazen Python .
Primer
Input: [' '] Output: Yes Explanation: In this, We are checking if the string is empty or not.
Preverite prazen niz v Pythonu
Tukaj so različne metode za preverjanje, ali je niz prazen ali ne v Pythonu.
- Uporaba len()
- Uporaba not()
- Uporaba not + str.strip()
- Uporaba not + str.isspace
- Uporaba seznamskega razumevanja
- Uporaba Bool
- Uporaba tračnih metod
- Uporaba in funkcija Operator + strip().
- Uporaba funkcije all().
- Uporaba poskusi/razen
Python Preverite prazen niz z uporabo Len()
Uporaba samo() je najbolj splošna metoda za preverjanje nizov ničelne dolžine. Čeprav ignorira dejstvo, da bi bilo treba niz s samo presledki praktično obravnavati kot prazen niz, tudi če ni nič.
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'> )> |
Izhod
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No
Python Check String Empty z uporabo Not()
Operator not lahko izvede tudi nalogo, podobno kot len() in preveri niz dolžine 0, vendar tako kot zgoraj meni, da je niz s samo presledki prav tako neprazen, kar praktično ne bi smelo biti res.
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'> )> |
Izhod
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No
Python prazen niz v ne poj + str.strip()
Težavo praznega niza + ničelne dolžine je mogoče odpraviti z uporabo strip(), strip() vrne true, če naleti na presledke, zato lahko preverjanje zanj reši težavo preverjanja čisto praznega niza.
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'> )> |
Izhod
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes
Preverite Prazen niz Python u sing not + str.isspace
Deluje na podoben način kot zgornja metoda in preverja presledke v nizu. Ta metoda je učinkovitejša, ker strip() zahteva tudi izvedbo operacije strip, ki prevzame računske obremenitve, če ne. prostorov je lepo število.
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'> )> |
Izhod
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes
Preverite, ali je niz prazen ali ne uporablja razumevanja seznama
Ta pristop vključuje razčlenitev besedila v seznam znakov z uporabo razumevanja seznama, nato pa ugotavljanje, ali je seznam prazen. Z oceno resničnosti seznama lahko ocenimo, ali je niz prazen ali ne.
Python3
string> => ''> x> => [> 'no'> if> len> (string)>> 0> else> 'yes'> ]> print> (x)> |
Izhod
['yes']
Preverite Python Empty String ali Not using Bool
Eden od pristopov je uporaba bool funkcija . Funkcija bool vrne False za prazne nize in True za neprazne nize. Tukaj je primer uporabe funkcije bool za preverjanje, ali je niz prazen ali 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> |
Izhod
The string is empty.
Uporabite lahko tudi funkcijo bool, da preverite, ali je niz prazen ali ne, potem ko ste odstranili vse presledke na začetku ali na koncu z metodo 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> |
Izhod
The string is empty.
Python Preverite, ali je niz je prazno z metodo traku
Tukaj bomo uporabili Python metode strip(). da preverite, ali je niz prazen ali 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'> )> |
Izhod
string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty
Preverite, ali je niz prazen ali se ne uporablja in funkcija operator + strip().
Pri tem pristopu se operator in uporablja za združevanje dveh preizkusov: ugotavljanje, ali niz ni None, in ugotavljanje, ali je odstranjena različica niza prazna. Presledki na začetku in na koncu so s funkcijo strip() izločeni iz niza.
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'> )> |
Izhod
string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty
Python Preverite, ali je niz je prazno z uporabo funkcije all().
Vrnjena vrednost funkcije all() zahteva Iterable kot vhod. Če je Iterable prazen ali so vsi njegovi člani resnični, je vrednost resnična. Funkcija all() lahko ugotovi, ali je niz prazen ali so vsi njegovi znaki napačni (prazen niz), tako da sprejme niz kot iterable znakov.
Python3
string> => ''> if> all> (char.isspace()> for> char> in> string):> > print> (> 'The string is empty'> )> else> :> > print> (> 'The string is not empty'> )> |
Izhod
The string is empty
Pristop bool za preverjanje, ali je niz prazen ali ne, ima časovna kompleksnost od O(1), saj preprosto preveri resničnostno vrednost niza, ki je operacija s konstantnim časom. The Pomožni prostor i s tudi O(1), ker zahteva samo eno logično spremenljivko za shranjevanje vrednosti resnice niza.
Python preveri prazen niz z uporabo Try/Except
Z uporabo bloka poskusi razen lahko v Pythonu določite, ali je niz prazen. Posebne izjeme, ki se lahko pojavijo med izvajanjem kode, lahko ujamete in obravnavate z uporabo bloka poskusi razen. Okoliščine, ko predvidevate verjetno napako, na primer ko preverjate prazen niz, lahko elegantno upravljate z uporabo bloka poskusi razen.
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.'> )> |
Izhod
The string is empty
Analiza kompleksnosti:
Ta koda ima konstantno časovno kompleksnost O(1), ker poskuša dostopati le do prvega znaka niza, kar traja enako količino časa ne glede na dolžino niza.