How to check if a string is empty in python?

mensanator at aol.com mensanator at aol.com
Fri May 4 14:19:11 EDT 2007


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.




More information about the Python-list mailing list