3
if var is not None and var !="" and var !=" ":
   # todo

can I write it like this?:

if var: 
   # todo

var is only String type.

1
  • @aug Not since OP wants whitespace to count as empty strings as well. Commented Sep 7, 2013 at 8:26

1 Answer 1

13

If you want to filter out space-only string (" "):

if var and var.strip():
    # ...

Becasue string that contain spaces is evaludated as True if used as predicate:

>>> bool("")
False

>>> bool("  ")
True
Sign up to request clarification or add additional context in comments.

3 Comments

I think if var.strip(): is equivalent to that.
@ShashankGupta: Not if var could be None.
Although obviously if ' ' is the only whitespace string that should be considered false, whereas ' ' * 2 or '\t' should be considered true as in the code in the question, then the answer is different :-)

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.