1

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?

2
  • I am curious about the function you are mentioning. Would you also post it here, I think it will be useful to have it? Commented Apr 30, 2022 at 4: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? Commented Apr 30, 2022 at 7:58

3 Answers 3

5

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!")
Sign up to request clarification or add additional context in comments.

Comments

2

You can use not s:

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

Comments

0

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

isinstance(s,str)

1 Comment

Why would you think that's the case? OP even type-hinted s to be a string!

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.