Python-programma om te controleren of String leeg is of niet
Python-strings zijn onveranderlijk en hebben een complexere behandeling bij het bespreken van hun bewerkingen. Merk op dat een string met spaties eigenlijk een lege string is, maar een grootte heeft die niet nul is. In dit artikel werd ook dat probleem en de oplossing ervoor besproken. Laten we verschillende methoden bekijken Controleer of String leeg is Python .
Voorbeeld
Input: [' '] Output: Yes Explanation: In this, We are checking if the string is empty or not.
Controleer Lege tekenreeks in Python
Hier zijn verschillende methoden om te controleren of een string leeg is of niet in Python.
- Len() gebruiken
- Gebruik niet()
- Gebruik not + str.strip()
- Gebruik not + str.isspace
- Lijstbegrip gebruiken
- Bool gebruiken
- Het gebruik van stripmethoden
- Gebruik en Operator + strip() Functie
- De functie all() gebruiken
- Met behulp van try/except
Python-controlereeks leeg met Len()
Gebruik makend van alleen() is de meest algemene methode om te controleren op tekenreeksen met lengte nul. Ook al negeert het het feit dat een string met alleen spaties ook praktisch als een lege string moet worden beschouwd, zelfs als deze niet nul is.
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'> )> |
Uitvoer
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No
Python-controletekenreeks leeg met behulp van Niet()
De not-operator kan ook de taak uitvoeren die vergelijkbaar is met len() en controleert op een tekenreeks met een lengte van 0, maar net als hierboven beschouwt hij de tekenreeks met alleen spaties ook als niet-leeg, wat praktisch niet waar zou moeten zijn.
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'> )> |
Uitvoer
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No
Python lege tekenreeks in zing niet + str.strip()
Het probleem van een lege string + lengte nul kan mogelijk worden opgelost door strip() te gebruiken. strip() retourneert true als het de spaties tegenkomt, waardoor het controleren ervan het probleem van het controleren op een puur lege string kan oplossen.
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'> )> |
Uitvoer
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes
Vink Lege String Python u aan zing niet + str.isspace
Werkt op dezelfde manier als de bovenstaande methode en controleert op spaties in de tekenreeks. Deze methode is efficiënter omdat strip() ook de stripbewerking moet uitvoeren, wat rekenlasten kost als dat niet het geval is. van spaties zijn van goed aantal.
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'> )> |
Uitvoer
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes
Controleer of String leeg is of geen Lijstbegrip gebruikt
Deze aanpak houdt in dat de tekst wordt geparseerd in een lijst met tekens met behulp van lijstbegrip, en vervolgens wordt bepaald of de lijst leeg is. We kunnen evalueren of de string al dan niet leeg is door de waarheidsgetrouwheid van de lijst te beoordelen.
Python3
string> => ''> x> => [> 'no'> if> len> (string)>> 0> else> 'yes'> ]> print> (x)> |
Uitvoer
['yes']
Vink Python Empty String aan of gebruik geen Bool
Eén benadering is het gebruik van de bool-functie . De bool-functie retourneert False voor lege tekenreeksen en True voor niet-lege tekenreeksen. Hier is een voorbeeld van het gebruik van de bool-functie om te controleren of een string leeg is of niet.
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> |
Uitvoer
The string is empty.
Je kunt ook de bool-functie gebruiken om te controleren of een string leeg is of niet, nadat je eventuele voor- of achterliggende spaties hebt verwijderd met behulp van de stripmethode:
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> |
Uitvoer
The string is empty.
Python Controleer of String is leeg met behulp van de stripmethode
Hier zullen we Python gebruiken strip() methoden om te controleren of de string leeg is of niet.
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'> )> |
Uitvoer
string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty
Controletekenreeks is leeg of gebruikt de functie Operator + strip() niet
Bij deze aanpak wordt de operator and gebruikt om twee tests te combineren: bepalen of de string niet Geen is en bepalen of de gestripte versie van de string leeg is. Voorloop- en volgspaties worden uit de string geëlimineerd door de functie 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'> )> |
Uitvoer
string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty
Python Controleer of String is leeg met behulp van de functie all().
De retourwaarde van de functie all() vereist een Iterable als invoer. Als de Iterable leeg is of als alle leden waar zijn, is de waarde waar. De functie all() kan bepalen of een string leeg is of dat alle karakters onwaar zijn (lege string) door de string te ontvangen als een iterabele reeks karakters.
Python3
string> => ''> if> all> (char.isspace()> for> char> in> string):> > print> (> 'The string is empty'> )> else> :> > print> (> 'The string is not empty'> )> |
Uitvoer
The string is empty
De bool-aanpak om te controleren of een string leeg is of niet, heeft een tijd complexiteit van O(1), omdat het eenvoudigweg de waarheidswaarde van de string controleert, wat een constante tijdbewerking is. De Hulpruimte i s ook O(1) omdat er slechts één enkele Booleaanse variabele nodig is om de waarheidswaarde van de string op te slaan.
Python controleert lege tekenreeks met Try/Except
Met behulp van een try-except blok kun je in Python bepalen of een string leeg is. Met behulp van het try-except-blok kunt u specifieke uitzonderingen opvangen en afhandelen die kunnen optreden terwijl uw code wordt uitgevoerd. U kunt omstandigheden waarin u een waarschijnlijke fout verwacht, op een elegante manier beheren, bijvoorbeeld wanneer u controleert op een lege tekenreeks, door een try-except-blok te gebruiken.
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.'> )> |
Uitvoer
The string is empty
Complexiteitsanalyse:
Deze code heeft een constante tijdscomplexiteit van O(1) omdat deze alleen probeert toegang te krijgen tot het eerste teken van de string, wat evenveel tijd kost, ongeacht de lengte van de string.