How to check whether a str(variable) is empty or not?
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.
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
Empty strings are False by default:
>>> if not "":
... print("empty")
...
empty
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