Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
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?
None
str
The string will be "truthy" if it is not None or has len > 0. Simply do the following check:
len > 0
if s: print("The string is valid!")
Add a comment
You can use not s:
not s
>>> not None True >>> not '' True >>> not 'foo' False
If your real goal is to find out if s is a string, you can use isinstance().
s
isinstance()
isinstance(s,str)
Required, but never shown
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.
Explore related questions
See similar questions with these tags.
None, but that's about it. I would expect type annotations to be able to guarantee that a variable is astrand notNone, where does that fail for you?