Python 문자열은 변경할 수 없으며 해당 작업을 논의할 때 처리가 더 복잡합니다. 공백이 있는 문자열은 실제로는 빈 문자열이지만 크기가 0이 아닙니다. 이 기사에서는 해당 문제와 해결 방법도 논의했습니다. 다양한 방법을 살펴보자 문자열이 비어 있는지 확인 파이썬 .
예
Input: [' '] Output: Yes Explanation: In this, We are checking if the string is empty or not.>
Python에서 빈 문자열 확인
Python에서 문자열이 비어 있는지 확인하는 다양한 방법이 있습니다.
- len() 사용
- not() 사용
- not + str.strip() 사용
- not + str.isspace 사용
- 목록 이해 사용
- 부울 사용
- 스트립 방법 사용
- 연산자 + Strip() 함수 사용
- all() 함수 사용
- 시도/제외 사용
Python Len()을 사용하여 문자열이 비어 있는지 확인
사용 오직() 길이가 0인 문자열을 확인하는 가장 일반적인 방법입니다. 공백만 있는 문자열도 0이 아니더라도 실제로는 빈 문자열로 간주되어야 한다는 사실을 무시하더라도 말이죠.
파이썬3
# 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'>)> |
>
>
산출
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No>
Python 검사 문자열이 비어 있음 Not()을 사용하여
not 연산자는 len()과 유사한 작업을 수행하고 길이가 0인 문자열을 검사할 수도 있지만 위와 마찬가지로 공백만 있는 문자열도 비어 있지 않은 것으로 간주하므로 실제로는 그렇지 않습니다.
파이썬3
# 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'>)> |
>
>
산출
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : No>
파이썬 빈 문자열 ~에 노래하지 말고 + str.strip()
빈 + 길이가 0인 문자열 문제는 Strip()을 사용하여 제거할 수 있으며, Strip()은 공백을 발견하면 true를 반환하므로 공백을 확인하면 순전히 빈 문자열을 확인하는 문제를 해결할 수 있습니다.
파이썬3
부분 파생 라텍스
# 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'>)> |
>
>
산출
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes>
빈 문자열 Python을 확인하십시오. 노래하지 말고 + str.isspace
위의 방법과 비슷한 방식으로 작동하며 문자열에 공백이 있는지 확인합니다. 이 방법은 스트립()이 계산 부하가 없는 경우 스트립 작업도 수행해야 하기 때문에 더 효율적입니다. 공간이 꽤 많습니다.
파이썬3
# 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'>)> |
>
>
산출
The zero length string without spaces is empty ? : Yes The zero length string with just spaces is empty ? : Yes>
문자열이 비어 있는지 또는 List Comprehension을 사용하지 않는지 확인
이 접근 방식에서는 목록 이해를 사용하여 텍스트를 문자 목록으로 구문 분석한 다음 목록이 비어 있는지 확인합니다. 목록의 진실성을 평가하여 문자열이 비어 있는지 여부를 평가할 수 있습니다.
파이썬3
foreach 타이프스크립트
string>=>''> x>=>[>'no'> if> len>(string)>>0> else> 'yes'>]> print>(x)> |
>
>
산출
['yes']>
Python 빈 문자열 또는 Bool을 사용하지 않는지 확인하십시오.
한 가지 접근 방식은 다음을 사용하는 것입니다. 부울 기능 . bool 함수는 빈 문자열에 대해 False를 반환하고 비어 있지 않은 문자열에 대해 True를 반환합니다. 다음은 bool 함수를 사용하여 문자열이 비어 있는지 확인하는 예입니다.
파이썬3
# 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> |
>
>
산출
The string is empty.>
또한, Strip 메소드를 사용하여 선행 또는 후행 공백을 제거한 후 bool 함수를 사용하여 문자열이 비어 있는지 여부를 확인할 수도 있습니다.
파이썬3
# 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> |
>
>
산출
The string is empty.>
Python 문자열인지 확인 스트립 방법을 사용하여 비어 있음
여기서는 Python을 사용하겠습니다. 스트립() 메소드 문자열이 비어 있는지 확인합니다.
파이썬3
#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'>)> |
얇은 알고리즘
>
>
산출
string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty>
문자열이 비어 있는지 또는 사용하지 않는지 확인하고 연산자 + 스트립() 함수
이 접근 방식에서는 and 연산자를 사용하여 문자열이 None이 아닌지 확인하고 문자열의 제거된 버전이 비어 있는지 확인하는 두 가지 테스트를 결합합니다. 선두 및 후행 공백 문자는 Strip() 함수에 의해 문자열에서 제거됩니다.
파이썬3
#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'>)> |
>
>
산출
대신에
string, string1 = '', with no spaces is empty string, string2 = ' ', with spaces is empty>
Python 문자열인지 확인 all() 함수를 사용하여 비어 있음
all() 함수의 반환 값에는 입력으로 Iterable이 필요합니다. Iterable이 비어 있거나 해당 멤버가 모두 true이면 값은 true입니다. all() 함수는 문자열을 반복 가능한 문자로 수신하여 문자열이 비어 있는지 또는 모든 문자가 거짓(빈 문자열)인지 확인할 수 있습니다.
파이썬3
string>=> ''> if> all>(char.isspace()>for> char>in> string):> >print>(>'The string is empty'>)> else>:> >print>(>'The string is not empty'>)> |
>
>
산출
The string is empty>
문자열이 비어 있는지 여부를 확인하는 bool 접근 방식에는 시간 복잡도 이는 O(1)의 상수 시간 연산인 문자열의 진리값을 단순히 확인하기 때문입니다. 그만큼 보조공간i 또한 문자열의 진리값을 저장하는 데 단일 부울 변수만 필요하기 때문에 O(1)입니다.
Python Try/Except를 사용하여 빈 문자열 확인
Try-Exception 블록을 사용하면 Python에서 문자열이 비어 있는지 확인할 수 있습니다. try-Exception 블록을 사용하면 코드가 실행되는 동안 발생할 수 있는 특정 예외를 포착하고 처리할 수 있습니다. 빈 문자열을 확인하는 등 오류 가능성이 예상되는 경우 try-Exception 블록을 사용하여 상황을 적절하게 관리할 수 있습니다.
파이썬3
# 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.'>)> |
>
>
산출
The string is empty>
복잡성 분석:
이 코드는 문자열의 첫 번째 문자에만 액세스하려고 시도하므로 문자열 길이에 관계없이 동일한 시간이 걸리기 때문에 O(1)의 일정한 시간 복잡도를 갖습니다.