Risposte:
Usa il str.isspace()metodo:
Restituisce
Truese nella stringa sono presenti solo caratteri bianchi e in casoFalsecontrario almeno un carattere .Un carattere è uno spazio se nel database dei caratteri Unicode (vedi unicodedata ), la sua categoria generale è Zs ("Separatore, spazio") o la sua classe bidirezionale è una di WS, B o S.
Combinalo con un caso speciale per la gestione della stringa vuota.
In alternativa, è possibile utilizzare str.strip()e verificare se il risultato è vuoto.
None, oppure''
if len(str) == 0 or str.isspace():
len(my_str) == 0può anche essere scritto not my_str.
>>> tests = ['foo', ' ', '\r\n\t', '', None]
>>> [not s or s.isspace() for s in tests]
[False, True, True, True, True]
Trueper None?
Vuoi usare il isspace()metodo
str. isspace ()
Restituisce vero se nella stringa sono presenti solo spazi bianchi e almeno un carattere, altrimenti falso.
Questo è definito su ogni oggetto stringa. Ecco un esempio di utilizzo per il tuo caso d'uso specifico:
if aStr and (not aStr.isspace()):
print aStr
Puoi usare il str.isspace()metodo
per coloro che si aspettano un comportamento come l'apache StringUtils.isBlank o Guava Strings.isNullOrEmpty :
if mystring and mystring.strip():
print "not blank string"
else:
print "blank string"
Controlla la lunghezza della lista data dal metodo split ().
if len(your_string.split()==0:
print("yes")
Oppure Confronta l'output del metodo strip () con null.
if your_string.strip() == '':
print("yes")
len()funziona su stringhe. Inoltre, l'OP non chiedeva di testare la stringa vuota, ma una stringa che fosse tutta spazio. Il tuo secondo metodo non è male però. Inoltre, le tue parentesi che circondano il condizionale non sono necessarie in Python.
==0con==1
if len(your_string.split())==0:-> if not your_string.split():, if your_string.strip() == '':-> if not your_string.strip():. In ogni caso, il primo è inferiore alle soluzioni esistenti e il secondo è già stato menzionato in altre risposte.
Ecco una risposta che dovrebbe funzionare in tutti i casi:
def is_empty(s):
"Check whether a string is empty"
return not s or not s.strip()
Se la variabile è Nessuna, si fermerà a not se non valuterà più (da allora not None == True). Apparentemente, il strip()metodo si occupa dei soliti casi di tab, newline, ecc.
not None == True è probabilmente più chiaro dirlo None is False. Inoltre, ==non dovrebbe essere usato per questi confronti.
Presumo nel tuo scenario, una stringa vuota è una stringa che è veramente vuota o che contiene tutto lo spazio bianco.
if(str.strip()):
print("string is not empty")
else:
print("string is empty")
Nota che questo non controlla None
Ho usato il seguente:
if str and not str.isspace():
print('not null and not empty nor whitespace')
else:
print('null or empty or whitespace')
None?
La somiglianza con il metodo statico stringa c # isNullOrWhiteSpace.
def isNullOrWhiteSpace(str):
"""Indicates whether the specified string is null or empty string.
Returns: True if the str parameter is null, an empty string ("") or contains
whitespace. Returns false otherwise."""
if (str is None) or (str == "") or (str.isspace()):
return True
return False
isNullOrWhiteSpace(None) -> True // None equals null in c#, java, php
isNullOrWhiteSpace("") -> True
isNullOrWhiteSpace(" ") -> True
return (str is None) or (str == "") or (str.isspace())
Nonee ""sono falsi, quindi puoi semplicemente:return not str or str.isspace()
U+00A0oALT+160. Sembra risolto in Python 2.7, tuttavia.