reza
reza

Reputation: 6358

how to check for non null string in python?

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?

Upvotes: 1

Views: 8888

Answers (3)

S&#246;ren
S&#246;ren

Reputation: 2432

You can use not s:

>>> not None
True
>>> not ''
True
>>> not 'foo'
False

Upvotes: 2

scotscotmcc
scotscotmcc

Reputation: 3113

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

isinstance(s,str)

Upvotes: 0

Jordan Bonecutter
Jordan Bonecutter

Reputation: 368

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!")

Upvotes: 5

Related Questions