반응형
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
반응형
'파이썬' 카테고리의 다른 글
파이썬 How to programmatically make a horizontal line in Qt (0) | 2020.10.05 |
---|---|
파이썬 MySQL 데이터베이스에 데이터를 어떻게 삽입 할 수 있습니까? (0) | 2020.10.05 |
파이썬 튜플에 대한 zip 함수 도움말 (0) | 2020.10.05 |
파이썬 Python dict를 kwargs로 변환 하시겠습니까? (0) | 2020.10.05 |
파이썬 디스크에 쓰지 않고 .zip 파일 다운로드 및 압축 해제 (0) | 2020.10.05 |
댓글