Empty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
if not myString:
This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:
if myString == "":
See the documentation on Truth Value Testing for other values that are false in Boolean contexts.
Answer from Andrew Clark on Stack OverflowEmpty strings are "falsy" (python 2 or python 3 reference), which means they are considered false in a Boolean context, so you can just do this:
if not myString:
This is the preferred way if you know that your variable is a string. If your variable could also be some other type then you should use:
if myString == "":
See the documentation on Truth Value Testing for other values that are false in Boolean contexts.
From PEP 8, in the “Programming Recommendations” section:
For sequences, (strings, lists, tuples), use the fact that empty sequences are false.
So you should use:
if not some_string:
or:
if some_string:
Just to clarify, sequences are evaluated to False or True in a Boolean context if they are empty or not. They are not equal to False or True.
What’s the cleanest way to do a python check if string is empty? - TestMu AI Community
empty string returns True upon checking if its contained in a non empty string
[Help] Getting blank string from subprocess.check_output
I remember having some similar issues. I checked my notes and I wound up doing it like this.
cmd = 'echo Some command string'
result = subprocess.run(cmd.split(), stdout=subprocess.PIPE, stderr=subprocess.PIPE)
stdout = result.stdout.decode('utf-8')
stderr = result.stderr.decode('utf-8')
status = 'COMPLETE' if result.returncode == 0 else 'FAILED' More on reddit.com What's the most pythonic way of checking if variable is None or empty string ""?
Videos
I'm trying to constantly check against any of those values but I don't want to keep repeating myself in code.
if variable is None or variable == "": do stuff
What are my options? Can I create somehow a class and check against that class?
if variable is MyNewClass: do stuff
How would I write such a class?
Thanks!