How to check if a string is empty in python?

Hamilton, William whamil1 at entergy.com
Fri May 4 14:31:51 EDT 2007


> -----Original Message-----
> From: mensanator at aol.com
> 
> On May 4, 5:02 am, Jaswant <mailme.gurpr... at gmail.com> wrote:
> > This is  a simple way to do it i think
> >
> > s=hello
> >
> > >>> if(len(s)==0):
> >
> > ...     print "Empty"
> > ... else:
> > ...     print s
> > ...
> > hello
> 
> But you are still making the assumption that s is a string.
> (BTW, you need quotes around your example.)
> 
> For example:
> 
> >>> print a,b
> 11 11
> 
> Can you tell which one is the string? I.e., which one had quotes
> around it?
> 
> If you correctly assume that it was b, then yes, your example works.
> 
> >>> print len(b)
> 2
> 
> If you incorrectly assume it was a, then the example doesn't work.
> 
> >>> print len(a)
> Traceback (most recent call last):
>   File "<pyshell#8>", line 1, in <module>
>     print len(a)
> TypeError: object of type 'int' has no len()
> 
> You have to know that a variable is a string before you try to do a
> len().
> 
> Dynamic typing is a feature, but that doesn't relieve you of the
> necessary tests.

Your point would be important if the question were "How can I tell if x
is an empty string?"  On the other hand, "How to check if a string is
empty?" implies that the OP already knows it is a string.  Maybe he's
been using string methods on it, maybe he got it from a function that he
knows provides a string. Maybe he's checked its type.  It doesn't really
matter, if he's aware it is a string he doesn't have to test it for
stringness.


---
-Bill Hamilton



More information about the Python-list mailing list