How to check whether a str(variable) is empty or not?

若如初见. 提交于 2019-12-03 18:28:00

问题


How do I make a:

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

condition?

(or something, because I am pretty sure that what I just wrote is completely wrong)

I am sort of trying to check if a random.choice from my list is ["",] (blank) or contains ["text",].


回答1:


You could just compare your string to the empty string:

if variable != "":
    etc.

But you can abbreviate that as follows:

if variable:
    etc.

Explanation: An if actually works by computing a value for the logical expression you give it: True or False. If you simply use a variable name (or a literal string like "hello") instead of a logical test, the rule is: An empty string counts as False, all other strings count as True. Empty lists and the number zero also count as false, and most other things count as true.




回答2:


The "Pythonic" way to check if a string is empty is:

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



回答3:


Empty strings are False by default:

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



回答4:


Just say if s or if not s. As in

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

So in your specific example, if I understand it correctly...

>>> 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



回答5:


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



回答6:


For python 3, you can use bool()

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



回答7:


How do i make an: if str(variable) == [contains text]: condition?

Perhaps the most direct way is:

if str(variable) != '':
  # ...

Note that the if not ... solutions test the opposite condition.




回答8:


Some time we have more spaces in between quotes, then use this approach

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

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



回答9:


if the variable contains text then:

len(variable) != 0

of it does not

len(variable) == 0




回答10:


string = "TEST"
try:
  if str(string):
     print "good string"
except NameError:
     print "bad string"


来源:https://stackoverflow.com/questions/9926446/how-to-check-whether-a-strvariable-is-empty-or-not

易学教程内所有资源均来自网络或用户发布的内容,如有违反法律规定的内容欢迎反馈
该文章没有解决你所遇到的问题?点击提问,说说你的问题,让更多的人一起探讨吧!