Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

python check string for emptieness - is this the elegant way [duplicate]

Tags:

python

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

can I write it like this?:

if var: 
   # todo

var is only String type.

like image 900
doniyor Avatar asked Dec 15 '25 12:12

doniyor


1 Answers

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
like image 80
falsetru Avatar answered Dec 19 '25 05:12

falsetru



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!