본문 바로가기
파이썬

파이썬 일반 및 유니 코드 빈 문자열에 대해 Python에서 "not None"테스트를 수행하는 가장 좋은 방법은 무엇입니까?

by º기록 2020. 10. 5.
반응형

Python 2.7에서는 빈 문자열을 반환 할 수도 있고 반환하지 않을 수도있는 API에서 함수를 호출하는 클래스를 작성하고 있습니다. 또한 빈 문자열은 유니 코드 u ""이거나 유니 코드가 아닌 "" 일 수 있습니다. 이것을 확인하는 가장 좋은 방법이 무엇인지 궁금합니다.

다음 코드는 빈 문자열에 적합하지만 빈 유니 코드 문자열에는 적합하지 않습니다.

class FooClass():
    string = ...
    string = might_return_normal_empty_string_or_unicode_empty_string(string)

    # Works for normal empty strings, not unicode:
    if string is not None:
        print "string is not an empty string."

대신 유니 코드에서 작동하도록하려면 다음과 같이 작성해야합니다.

class BarClass():
    string = ...
    string = might_return_normal_empty_string_or_unicode_empty_string(string)

    # Works for unicode empty strings, not normal:
    if string is not u"":
        print "string is not an empty string."

... 그리고 비 유니 코드와 유니 코드의 빈 문자열 모두에 대해 작동하도록하려면 다음과 같이하십시오.

class FooBarClass():
    string = ...
    string = might_return_normal_empty_string_or_unicode_empty_string(string)

    # Works for both normal and unicode empty strings:
    if string is not u"" or None:
        print "string is not an empty string."

세 번째 방법이이를 수행하는 가장 좋은 방법입니까, 아니면 더 나은 방법이 있습니까? u ""를 작성하는 것이 나에게 너무 어렵게 느껴지기 때문에 묻는다. 하지만 그것이 최선의 방법이라면 그렇게하세요. :) 도움을 주셔서 감사합니다.

 

해결 방법

 

빈 문자열은 거짓으로 간주됩니다.

if string:
    # String is not empty.
else:
    # String is empty.

 

참조 페이지 https://stackoverflow.com/questions/5690491

 

 

반응형

댓글