Home > Net >  how to check for non null string in python?
how to check for non null string in python?

Time:04-30

Total newbie python question. I find myself having to write to the following code

s: str
if s is None or len(s) <= 0

to check for string validation.

I finally wrote a tiny function to do that for me.

Is there a more pythantic way of doing this?

CodePudding user response:

The string will be "truthy" if it is not None or has len > 0. Simply do the following check:

if s:
  print("The string is valid!")

CodePudding user response:

You can use not s:

>>> s = None
>>> print(not s)
True
>>> s = ''
>>> print(not s)
True
>>> s = 'foo'
>>> print(not s)
False

CodePudding user response:

If your real goal is to find out if s is a string, you can use isinstance().

isinstance(s,str)

CodePudding user response:

The simplest I can think of:

print(s is None)

The possible outputs are either True or False.

Just for reference which might be useful, a similar topic was raised for checking multiple variables here.

  • Related