Python-program til at kontrollere, om strengen er tom eller ej
Python-strenge er uforanderlige og har mere kompleks håndtering, når de diskuterer deres operationer. Bemærk, at en streng med mellemrum faktisk er en tom streng, men har en størrelse, der ikke er nul. Denne artikel diskuterede også dette problem og løsningen på det. Lad os se forskellige metoder til Tjek, om strengen er tom Python .
Eksempel
Input: [' '] Output: Yes Explanation: In this, We are checking if the string is empty or not.
Tjek Tom streng i Python
Her er forskellige metoder til at kontrollere, om en streng er tom eller ej i Python.
- Brug af len()
- Bruger not()
- Bruger not + str.strip()
- Bruger not + str.isspace
- Brug af listeforståelse
- Bruger Bool
- Brug af stripmetoder
- Brug og Operator + strip() Funktion
- Bruger funktionen all()
- Bruger try/undtagen
Python Check String Empty ved hjælp af Len()
Ved brug af kun() er den mest generiske metode til at tjekke for nul-længde strenge. Selvom det ignorerer det faktum, at en streng med kun mellemrum også praktisk taget bør betragtes som en tom streng, selvom den ikke er nul.
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'> )> |
Produktion
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No
Python Check String Tom ved hjælp af Not()
Not-operatoren kan også udføre opgaven svarende til len() og tjekker for 0-længde streng, men på samme måde som ovenstående, anser den strengen med kun mellemrum også for at være ikke-tom, hvilket praktisk talt ikke burde være sandt.
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'> )> |
Produktion
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No
Python tom streng i sing not + str.strip()
Problemet med en tom + nul-længde streng kan muligvis fjernes ved at bruge strip(), strip() returnerer sand hvis den støder på mellemrummene, derfor kan tjek for det løse problemet med at tjekke for en rent tom streng.
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'> )> |
Produktion
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes
Tjek Empty String Python u synge ikke + str.isspace
Fungerer på samme måde som metoden ovenfor og tjekker for mellemrum i strengen. Denne metode er mere effektiv, fordi strip() kræver at udføre stripoperationen også, som tager beregningsbelastninger, hvis nej. af mellemrum er et godt antal.
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'> )> |
Produktion
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes
Tjek, om strengen er tom eller ikke ved hjælp af listeforståelse
Denne fremgangsmåde indebærer at analysere teksten til en liste af tegn ved hjælp af listeforståelse, og derefter bestemme, om listen er tom. Vi kan vurdere, om strengen er tom eller ej, ved at vurdere sandheden af listen.
Python3
string> => ''> x> => [> 'no'> if> len> (string)>> 0> else> 'yes'> ]> print> (x)> |
Produktion
['yes']
Tjek Python Empty String or Not using Bool
En tilgang er at bruge bool funktion . Bool-funktionen returnerer False for tomme strenge og True for ikke-tomme strenge. Her er et eksempel på brug af bool-funktionen til at kontrollere, om en streng er tom eller ej.
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> |
Produktion
The string is empty.
Du kan også bruge bool-funktionen til at kontrollere, om en streng er tom eller ej, efter at du har fjernet indledende eller efterstillede mellemrum ved hjælp af stripmetoden:
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> |
Produktion
The string is empty.
Python Tjek om String er tom ved hjælp af Strip-metoden
Her vil vi bruge Python strip() metoder for at kontrollere, at strengen er tom eller ej.
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'> )> |
Produktion
string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty
Tjek strengen er tom eller bruger ikke og Operator + strip() funktion
I denne tilgang bruges og-operatoren til at kombinere to tests: afgøre, om strengen ikke er Ingen, og afgøre, om strengens strippede version er tom. Førende og efterstillede mellemrumstegn fjernes fra strengen af funktionen 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'> )> |
Produktion
string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty
Python Tjek om String er tom ved at bruge all()-funktionen
Returværdien af funktionen all() kræver en Iterable som input. Hvis Iterable er tom, eller alle dens medlemmer er sande, er værdien sand. Funktionen all() kan bestemme, om en streng er tom, eller om alle dens tegn er falske (tom streng) ved at modtage strengen som en iterabel af tegn.
Python3
string> => ''> if> all> (char.isspace()> for> char> in> string):> > print> (> 'The string is empty'> )> else> :> > print> (> 'The string is not empty'> )> |
Produktion
The string is empty
Bool-tilgangen til at kontrollere, om en streng er tom eller ej, har en tidskompleksitet af O(1), da den blot kontrollerer strengens sandhedsværdi, som er en konstant tidsoperation. Det Hjælpeplads i s også O(1), da det kun kræver en enkelt boolesk variabel for at gemme strengens sandhedsværdi.
Python Kontroller tom streng ved hjælp af Try/Except
Ved at bruge en try-except-blok kan du bestemme i Python, om en streng er tom. Du kan fange og håndtere specifikke undtagelser, der kan opstå, mens din kode bliver eksekveret, ved at bruge try-except-blokken. Du kan elegant håndtere omstændigheder, når du forudser en sandsynlig fejl, såsom når du tjekker for en tom streng, ved at bruge en try-except-blok.
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.'> )> |
Produktion
The string is empty
Kompleksitetsanalyse:
Denne kode har en konstant tidskompleksitet på O(1), fordi den kun forsøger at få adgang til det første tegn i strengen, hvilket tager den samme tid uanset længden af strengen.