Programma Python per verificare se la stringa è vuota o no

Le stringhe Python sono immutabili e hanno una gestione più complessa quando si discutono le loro operazioni. Tieni presente che una stringa con spazi è in realtà una stringa vuota ma ha una dimensione diversa da zero. Questo articolo ha discusso anche di questo problema e della sua soluzione. Vediamo diversi metodi di Controlla se la stringa è vuota Pitone .

Esempio

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

Controlla Stringa vuota in Python

Ecco diversi metodi per verificare se una stringa è vuota o meno in Python.

  • Usando len()
  • Usando not()
  • Usando not + str.strip()
  • Usando not + str.isspace
  • Utilizzando la comprensione delle liste
  • Utilizzando Bool
  • Utilizzando metodi di strip
  • Utilizzo della funzione and Operator + strip()
  • Utilizzando la funzione all()
  • Utilizzando prova/eccetto

Python controlla la stringa vuota usando Len()

Utilizzando soltanto() è il metodo più generico per verificare la presenza di stringhe di lunghezza zero. Anche se ignora il fatto che una stringa con solo spazi dovrebbe essere praticamente considerata una stringa vuota anche se è diversa da zero.

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

Produzione

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

Stringa di controllo Python vuota usando Not()

L'operatore not può anche eseguire l'attività simile a len() e controlla la stringa di lunghezza 0, ma come sopra, considera anche la stringa con solo spazi come non vuota, il che non dovrebbe essere praticamente vero.

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

Produzione

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

Stringa vuota di Python In non cantare + str.strip()

Il problema di una stringa vuota + di lunghezza zero può essere eventualmente rimosso utilizzando strip(), strip() restituisce true se incontra spazi, quindi controllarlo può risolvere il problema del controllo di una stringa puramente vuota.

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

Produzione

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

Controlla la stringa vuota Python u cantare non + str.isspace

Funziona in modo simile al metodo precedente e controlla gli spazi nella stringa. Questo metodo è più efficiente perché strip() richiede di eseguire anche l'operazione di strip che, in caso contrario, richiede carichi di calcolo. gli spazi sono di buon numero.

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

Produzione

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

Controlla se la stringa è vuota o non utilizza la comprensione dell'elenco

Questo approccio implica l'analisi del testo in un elenco di caratteri utilizzando la comprensione dell'elenco, quindi la determinazione se l'elenco è vuoto. Possiamo valutare se la stringa è vuota o meno valutando la veridicità della lista.

Python3




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

Produzione

['yes'] 

Controlla Python Stringa vuota o Non usi Bool

Un approccio sta utilizzando il file funzione bool . La funzione bool restituisce False per stringhe vuote e True per stringhe non vuote. Ecco un esempio di utilizzo della funzione bool per verificare se una stringa è vuota o meno.

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>

Produzione

The string is empty. 

Puoi anche utilizzare la funzione bool per verificare se una stringa è vuota o meno dopo aver rimosso eventuali spazi bianchi iniziali o finali utilizzando il 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>

Produzione

The string is empty. 

Python Controlla se String è vuoto utilizzando il metodo Strip

Qui useremo Python metodi strip() per verificare che la stringa sia vuota o meno.

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

Produzione

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

Controlla che la stringa sia vuota o non utilizzata e la funzione Operatore + strip()

In questo approccio, l'operatore and viene utilizzato per combinare due test: determinare se la stringa non è None e determinare se la versione rimossa della stringa è vuota. Gli spazi bianchi iniziali e finali vengono eliminati dalla stringa dalla funzione 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'> )>

Produzione

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

Python Controlla se String è vuoto utilizzando la funzione all()

Il valore restituito dalla funzione all() richiede un Iterable come input. Se l'Iterable è vuoto o tutti i suoi membri sono veri, il valore è vero. La funzione all() può determinare se una stringa è vuota o se tutti i suoi caratteri sono falsi (stringa vuota) ricevendo la stringa come un iterabile di caratteri.

Python3




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

Produzione

The string is empty 

L'approccio bool per verificare se una stringa è vuota o meno ha a complessità temporale di O(1), poiché controlla semplicemente il valore di verità della stringa, che è un'operazione a tempo costante. IL Spazio ausiliario i è anche O(1) poiché richiede solo una singola variabile booleana per memorizzare il valore di verità della stringa.

Python controlla la stringa vuota usando Try/Except

Usando un blocco try-eccetto, puoi determinare in Python se una stringa è vuota. Puoi rilevare e gestire eccezioni specifiche che potrebbero verificarsi durante l'esecuzione del codice utilizzando il blocco try-Exception. Puoi gestire con garbo le circostanze in cui prevedi un probabile errore, ad esempio quando controlli una stringa vuota, utilizzando un blocco try-eccetto.

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

Produzione

The string is empty 

Analisi della complessità:
Questo codice ha una complessità temporale costante pari a O(1) perché tenta di accedere solo al primo carattere della stringa, che impiega la stessa quantità di tempo indipendentemente dalla lunghezza della stringa.