[python] str (변수)가 비어 있는지 확인하는 방법은 무엇입니까?

어떻게 만드나요 :

if str(variable) == [contains text]:

질환?

(또는 내가 방금 쓴 내용이 완전히 잘못되었다고 확신하기 때문에)

random.choice내 목록의 a가 ["",](비어 있음) 또는 포함되어 있는지 확인하려고합니다 ["text",].



답변

문자열을 빈 문자열과 비교할 수 있습니다.

if variable != "":
    etc.

그러나 다음과 같이 축약 할 수 있습니다.

if variable:
    etc.

설명 :은 if실제로 사용자가 제공 한 논리식 True또는 False. 논리 테스트 대신 변수 이름 (또는 “hello”와 같은 리터럴 문자열)을 사용하는 경우 규칙은 다음과 같습니다. 빈 문자열은 False로 계산하고 다른 모든 문자열은 True로 계산합니다. 빈 목록과 숫자 0도 거짓으로 간주되며 다른 대부분은 참으로 간주됩니다.


답변

문자열이 비어 있는지 확인하는 “Pythonic”방법은 다음과 같습니다.

import random
variable = random.choice(l)
if variable:
    # got a non-empty string
else:
    # got an empty string


답변

빈 문자열은 기본적으로 False입니다.

>>> if not "":
...     print("empty")
...
empty


답변

if s또는 라고 말 if not s하세요. 에서와 같이

s = ''
if not s:
    print 'not', s

따라서 귀하의 특정 예에서 올바르게 이해하면 …

>>> import random
>>> l = ['', 'foo', '', 'bar']
>>> def default_str(l):
...     s = random.choice(l)
...     if not s:
...         print 'default'
...     else:
...         print s
... 
>>> default_str(l)
default
>>> default_str(l)
default
>>> default_str(l)
bar
>>> default_str(l)
default


답변

파이썬 3의 경우 bool ()을 사용할 수 있습니다.

>>> bool(None)
False
>>> bool("")
False
>>> bool("a")
True
>>> bool("ab")
True
>>> bool("9")
True


답변

언젠가 따옴표 사이에 더 많은 공백이 있으면이 방법을 사용합니다.

a = "   "
>>> bool(a)
True
>>> bool(a.strip())
False

if not a.strip():
    print("String is empty")
else:
    print("String is not empty")


답변

element = random.choice(myList)
if element:
    # element contains text
else:
    # element is empty ''