0

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?

reza
  • 5,972
  • 15
  • 84
  • 126
  • I am curious about the function you are mentioning. Would you also post it here, I think it will be useful to have it? – apingaway Apr 30 '22 at 04:29
  • 1
    Other than in C, a string can not be null. A string can be empty and a variable can reference `None`, but that's about it. I would expect type annotations to be able to guarantee that a variable is a `str` and not `None`, where does that fail for you? – Ulrich Eckhardt Apr 30 '22 at 07:58

3 Answers3

3

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

You can use not s:

>>> not None
True
>>> not ''
True
>>> not 'foo'
False
Sören
  • 1,803
  • 2
  • 16
  • 23
0

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

isinstance(s,str)
scotscotmcc
  • 2,719
  • 1
  • 6
  • 29