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
element = random.choice(myList)
if element:
# element contains text
else:
# element is empty ''
파이썬 3의 경우 bool ()을 사용할 수 있습니다.
>>> bool(None)
False
>>> bool("")
False
>>> bool("a")
True
>>> bool("ab")
True
>>> bool("9")
True
if str(variable) == [contains text]:
조건 은 어떻게 만드 나요?
아마도 가장 직접적인 방법은 다음과 같습니다.
if str(variable) != '':
# ...
점을 유의 if not ...
솔루션은 테스트 반대의 상태를.
언젠가 따옴표 사이에 더 많은 공백이있는 경우이 방법을 사용합니다.
a = " "
>>> bool(a)
True
>>> bool(a.strip())
False
if not a.strip():
print("String is empty")
else:
print("String is not empty")
변수에 텍스트가 포함 된 경우 :
len(variable) != 0
그것의
len(variable) == 0
string = "TEST"
try:
if str(string):
print "good string"
except NameError:
print "bad string"
참고 URL : https://stackoverflow.com/questions/9926446/how-to-check-whether-a-strvariable-is-empty-or-not
'Nice programing' 카테고리의 다른 글
typescript에서 svg 파일을 가져올 수 없습니다. (0) | 2020.11.30 |
---|---|
IntelliJ에서 전체 프로젝트에 대해 "단축 명령 줄"방법을 구성하는 방법 (0) | 2020.11.30 |
Bind () 대신 Join ()을 사용하는 모나드 (0) | 2020.11.29 |
Python 2.7의 분할 (0) | 2020.11.29 |
스파크 실행기 번호, 코어 및 실행기 메모리를 조정하는 방법은 무엇입니까? (0) | 2020.11.29 |