473,320 Members | 1,936 Online
Bytes | Software Development & Data Engineering Community
Post Job

Home Posts Topics Members FAQ

Join Bytes to post your question to a community of 473,320 software developers and data experts.

How to check if a string is empty in python?

How to check if a string is empty in python?
if(s == "") ??

May 2 '07 #1
31 88548
A simple

if s:
print "not empty"
else:
print "empty"

will do.
-Basilisk96

May 2 '07 #2
On May 2, 1:35 pm, noagbodjivic...@gmail.com wrote:
How to check if a string is empty in python?
if(s == "") ??


Empty strings and containers are false; so
one can write

if (not s):
print "something..."
--
Hope this helps,
Steven

May 2 '07 #3
On May 2, 3:49 pm, Basilisk96 <basilis...@gmail.comwrote:
A simple

if s:
print "not empty"
else:
print "empty"

will do.
How do you know that s is a string?
>
-Basilisk96

May 2 '07 #4
How do you know that s is a string?

It's a presumption based on the original problem statement.

The example shown is a simple T/F check, which happens to determine
the "emptiness" of strings.
If type checking is absolutely necessary, one could use

if isinstance(s, basestring):
if s:
print "not empty"
else:
print "empty"
May 2 '07 #5
no*************@gmail.com schrieb:
How to check if a string is empty in python?
if(s == "") ??
Exactly so. "not s" works as well.

Martin
May 2 '07 #6
On May 3, 6:35 am, noagbodjivic...@gmail.com wrote:
How to check if a string is empty in python?
if(s == "") ??
Please lose the parentheses.
if s == "": will work.
So will if not s:

Have you worked through the tutorial yet?

May 2 '07 #7
On Wed, 02 May 2007 13:35:47 -0700, noagbodjivictor wrote:
How to check if a string is empty in python?
if(s == "") ??
In no particular order, all of these methods will work:
# test s is equal to another empty string
if s == "":

# assuming s is a string, test that it is empty
if not s:

# test s is a string and it is empty
if isinstance(s, str) and not s:

# test s has length 0
if len(s) == 0:

# test the length of s evaluates as false
if not len(s):

# a long way to test the length of s
if s.__len__() < 1:

# a stupid way to test s is empty
if bool(s) == False:

# a REALLY stupid way to test s is empty
if (bool(s) == False) == True:

# test that appending s to itself is itself
if s+s == s:

# test that s has none of any character
if not filter(None, [1 + s.find(chr(n)) for n in range(256)]):

That last one is really only good for wasting CPU cycles.
--
Steven.

May 2 '07 #8
no*************@gmail.com a écrit :
How to check if a string is empty in python?
if(s == "") ??
if not s:
print "s is empty"
May 2 '07 #9
On May 3, 8:50 am, Steven D'Aprano
<s...@REMOVE.THIS.cybersource.com.auwrote:
On Wed, 02 May 2007 13:35:47 -0700, noagbodjivictor wrote:
How to check if a string is empty in python?
if(s == "") ??

In no particular order, all of these methods will work:
[snip]
>
# test that s has none of any character
if not filter(None, [1 + s.find(chr(n)) for n in range(256)]):

That last one is really only good for wasting CPU cycles.
Have you considered
if not re.match(".+$", s):
?
May 2 '07 #10
me********@aol.com a écrit :
On May 2, 3:49 pm, Basilisk96 <basilis...@gmail.comwrote:
>>A simple

if s:
print "not empty"
else:
print "empty"

will do.


How do you know that s is a string?
Why do you want to know if it's a string ?

May 2 '07 #11
On May 2, 6:41 pm, Bruno Desthuilliers
<bdesth.quelquech...@free.quelquepart.frwrote:
mensana...@aol.com a écrit :
On May 2, 3:49 pm, Basilisk96 <basilis...@gmail.comwrote:
>A simple
>if s:
print "not empty"
else:
print "empty"
>will do.
How do you know that s is a string?

Why do you want to know if it's a string ?
>>import gmpy
gmpy.mpz(11)
mpz(11)
>>gmpy.mpz('11',10)
mpz(11)
>>gmpy.mpz(11,10)
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
gmpy.mpz(11,10)
TypeError: gmpy.mpz() with numeric argument needs exactly 1 argument

The mpz conversion takes two arguments if and only if s is a string,
else it takes 1 argument. So being non-empty is insufficient.

May 2 '07 #12
On May 2, 5:50 pm, Steven D'Aprano
<s...@REMOVE.THIS.cybersource.com.auwrote:
On Wed, 02 May 2007 13:35:47 -0700, noagbodjivictor wrote:
How to check if a string is empty in python?
if(s == "") ??

In no particular order, all of these methods will work:

# test s is equal to another empty string
if s == "":

# assuming s is a string, test that it is empty
if not s:

# test s is a string and it is empty
if isinstance(s, str) and not s:

# test s has length 0
if len(s) == 0:

# test the length of s evaluates as false
if not len(s):

# a long way to test the length of s
if s.__len__() < 1:

# a stupid way to test s is empty
if bool(s) == False:

# a REALLY stupid way to test s is empty
if (bool(s) == False) == True:
LOL
# test that appending s to itself is itself
if s+s == s:

# test that s has none of any character
if not filter(None, [1 + s.find(chr(n)) for n in range(256)]):

That last one is really only good for wasting CPU cycles.
and the other ones are... ?
--
Steven.
May 3 '07 #13
In article <11**********************@h2g2000hsg.googlegroups. com>,
Dustan <Du**********@gmail.comwrote:
On May 2, 5:50 pm, Steven D'Aprano
<s...@REMOVE.THIS.cybersource.com.auwrote:
On Wed, 02 May 2007 13:35:47 -0700, noagbodjivictor wrote:
How to check if a string is empty in python?
if(s == "") ??
In no particular order, all of these methods will work:

# test s is equal to another empty string
if s == "":

# assuming s is a string, test that it is empty
if not s:

# test s is a string and it is empty
if isinstance(s, str) and not s:

# test s has length 0
if len(s) == 0:

# test the length of s evaluates as false
if not len(s):

# a long way to test the length of s
if s.__len__() < 1:

# a stupid way to test s is empty
if bool(s) == False:

# a REALLY stupid way to test s is empty
if (bool(s) == False) == True:

LOL
# test that appending s to itself is itself
if s+s == s:

# test that s has none of any character
if not filter(None, [1 + s.find(chr(n)) for n in range(256)]):

That last one is really only good for wasting CPU cycles.

and the other ones are... ?
--
Steven.
s.join("foo") == "foo"

for c in s:
raise "it's not empty"
May 3 '07 #14
On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote:
for c in s:
raise "it's not empty"
String exceptions are depreciated and shouldn't be used.

http://docs.python.org/api/node16.html

--
Steven D'Aprano
May 3 '07 #15
me********@aol.com <me********@aol.comwrote:
...
>import gmpy
gmpy.mpz(11)
mpz(11)
>gmpy.mpz('11',10)
mpz(11)
>gmpy.mpz(11,10)

Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
gmpy.mpz(11,10)
TypeError: gmpy.mpz() with numeric argument needs exactly 1 argument

The mpz conversion takes two arguments if and only if s is a string,
else it takes 1 argument. So being non-empty is insufficient.
Being a string AND being non-empty is insufficient too -- just try

gmpy.mpz("Hello, I am a string and definitely not empy!", 10)

on for size.
Alex
May 3 '07 #16
Steven D'Aprano <st***@REMOVEME.cybersource.com.auwrote:
On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote:
for c in s:
raise "it's not empty"

String exceptions are depreciated and shouldn't be used.

http://docs.python.org/api/node16.html
They're actually deprecated, not depreciated.

Searching define:deprecated -- first hit:

In computer software standards and documentation, deprecation is the
gradual phasing-out of a software or programming language feature.
en.wikipedia.org/wiki/Deprecated

and the other four hits are fine too.

Searching define:depreciated , we move almost entirely into accounting
and finance, except:

http://en.wikipedia.org/wiki/Depreciated
"""
Depreciated is often confused or used as a stand-in for "deprecated";
see deprecation for the use of depreciation in computer software
"""
Alex
May 3 '07 #17
On Wed, 02 May 2007 21:59:56 -0700, Alex Martelli wrote:
Steven D'Aprano <st***@REMOVEME.cybersource.com.auwrote:
>On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote:
for c in s:
raise "it's not empty"

String exceptions are depreciated and shouldn't be used.

http://docs.python.org/api/node16.html

They're actually deprecated, not depreciated.
Er, um... oh yeah... I knew that...

I mean... yes, that was deliberate, to see who was paying attention. Well
done Alex!

--
Steven D'Aprano

May 3 '07 #18
On May 2, 5:50 pm, Steven D'Aprano
<s...@REMOVE.THIS.cybersource.com.auwrote:
On Wed, 02 May 2007 13:35:47 -0700, noagbodjivictor wrote:
How to check if a string is empty in python?
if(s == "") ??

In no particular order, all of these methods will work:

# test s is equal to another empty string
if s == "":

# assuming s is a string, test that it is empty
if not s:

# test s is a string and it is empty
if isinstance(s, str) and not s:

# test s has length 0
if len(s) == 0:

# test the length of s evaluates as false
if not len(s):

# a long way to test the length of s
if s.__len__() < 1:

# a stupid way to test s is empty
if bool(s) == False:

# a REALLY stupid way to test s is empty
if (bool(s) == False) == True:

# test that appending s to itself is itself
if s+s == s:
Being the slow person that I am, it really did take me this long to
find a mistake.
s+s != 'appending'
s+s == 'concatenation'
# test that s has none of any character
if not filter(None, [1 + s.find(chr(n)) for n in range(256)]):

That last one is really only good for wasting CPU cycles.

--
Steven.

May 3 '07 #19
Ant
On May 3, 5:59 am, a...@mac.com (Alex Martelli) wrote:
Steven D'Aprano <s...@REMOVEME.cybersource.com.auwrote:
On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote:
for c in s:
raise "it's not empty"
String exceptions are depreciated and shouldn't be used.
http://docs.python.org/api/node16.html

They're actually deprecated, not depreciated.
In Steven's defence, string exceptions *are* probably worth less, as
there's no longer such a demand for them.

--
Ant...

May 3 '07 #20
In article <11**********************@n59g2000hsh.googlegroups .com>,
Ant <an****@gmail.comwrote:
On May 3, 5:59 am, a...@mac.com (Alex Martelli) wrote:
Steven D'Aprano <s...@REMOVEME.cybersource.com.auwrote:
On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote:
for c in s:
raise "it's not empty"
String exceptions are depreciated and shouldn't be used.
>http://docs.python.org/api/node16.html
They're actually deprecated, not depreciated.

In Steven's defence, string exceptions *are* probably worth less, as
there's no longer such a demand for them.
You just wait until they start showing up on Antiques Roadshow :-)
May 3 '07 #21
On May 2, 11:59 pm, a...@mac.com (Alex Martelli) wrote:
mensana...@aol.com <mensana...@aol.comwrote:

...
>>import gmpy
>>gmpy.mpz(11)
mpz(11)
>>gmpy.mpz('11',10)
mpz(11)
>>gmpy.mpz(11,10)
Traceback (most recent call last):
File "<pyshell#38>", line 1, in <module>
gmpy.mpz(11,10)
TypeError: gmpy.mpz() with numeric argument needs exactly 1 argument
The mpz conversion takes two arguments if and only if s is a string,
else it takes 1 argument. So being non-empty is insufficient.

Being a string AND being non-empty is insufficient too -- just try

gmpy.mpz("Hello, I am a string and definitely not empy!", 10)

on for size.

Alex
>>import gmpy
gmpy.mpz("Hello, I am a string and definitely not empy!", 10)
Traceback (most recent call last):
File "<pyshell#4>", line 1, in <module>
gmpy.mpz("Hello, I am a string and definitely not empy!", 10)
ValueError: invalid digits

But you don't get a TypeError, you get a ValueError. And you might
scratch your head over
>>gmpy.mpz('zzz',26)
Traceback (most recent call last):
File "<pyshell#5>", line 1, in <module>
gmpy.mpz('zzz',26)
ValueError: invalid digits

until you remember that base 26 is 0-9a-p, not a-z.

May 3 '07 #22
me********@aol.com wrote:
On May 2, 3:49 pm, Basilisk96 <basilis...@gmail.comwrote:
>A simple

if s:
print "not empty"
else:
print "empty"

will do.

How do you know that s is a string?
Seems like a fair assumption given the OP's question and example.
May 3 '07 #23
On May 3, 2:03 pm, John Salerno <johnj...@NOSPAMgmail.comwrote:
mensana...@aol.com wrote:
On May 2, 3:49 pm, Basilisk96 <basilis...@gmail.comwrote:
A simple
if s:
print "not empty"
else:
print "empty"
will do.
How do you know that s is a string?

Seems like a fair assumption given the OP's question and example.
A fair assumption for languages other than Python.

Just because s was a string at some point in the past
doesn't mean it's a string now.

May 3 '07 #24
This is a simple way to do it i think
s=hello
>>if(len(s)==0):
.... print "Empty"
.... else:
.... print s
....
hello

May 4 '07 #25
On 4 May 2007 03:02:37 -0700, Jaswant <ma*************@gmail.comwrote:
This is a simple way to do it i think
s=hello
>if(len(s)==0):
.... print "Empty"
.... else:
.... print s
....
hello
Not as simple as " If not s: "

and nowhere near as simple as " print s or 'Empty' " :) :)

>>s = ''
print s or 'Empty'
Empty
>>s = 'hello'
print s or 'Empty'
hello
>>>
May 4 '07 #26
On May 4, 5:02 am, Jaswant <mailme.gurpr...@gmail.comwrote:
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.

May 4 '07 #27
Alex Martelli wrote:
Steven D'Aprano <st***@REMOVEME.cybersource.com.auwrote:
>On Wed, 02 May 2007 21:19:54 -0400, Roy Smith wrote:
>>for c in s:
raise "it's not empty"
String exceptions are depreciated and shouldn't be used.

http://docs.python.org/api/node16.html

They're actually deprecated, not depreciated.

Searching define:deprecated -- first hit:

In computer software standards and documentation, deprecation is the
gradual phasing-out of a software or programming language feature.
en.wikipedia.org/wiki/Deprecated

and the other four hits are fine too.

Searching define:depreciated , we move almost entirely into accounting
and finance, except:

http://en.wikipedia.org/wiki/Depreciated
"""
Depreciated is often confused or used as a stand-in for "deprecated";
see deprecation for the use of depreciation in computer software
"""
Alex
Isn't deprecated like depreciated but not quite to zero yet?

-Larry
May 4 '07 #28
On May 4, 1:31 pm, "Hamilton, William " <wham...@entergy.comwrote:
-----Original Message-----
From: mensana...@aol.com
On May 4, 5:02 am, Jaswant <mailme.gurpr...@gmail.comwrote:
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.
OTOH, some don't know enough to quote their string literals, so I
think
my point is well justified.
>
---
-Bill Hamilton
May 5 '07 #29
Larry Bates <la*********@websafe.comwrote:
...
Isn't deprecated like depreciated but not quite to zero yet?
No. "To deprecate" comes from a Latin verb meaning "to ward off a
disaster by prayer"; when you're saying you deprecate something, you're
saying you're praying for that something to disappear, go away; in a
secular context, you're earnestly imploring people to NOT do it.

"To depreciate" comes from a Latin verb meaning "to reduce the price";
when you're saying you depreciate something, you're saying you put on
that something a lower price (and, by extension, a lower value) than it
has (or, more commonly, used to have). You're not necessarily saying
it's worth nothing at all (accountants sometimes deem an asset "fully
depreciated" to mean something close to that, but the adverb "fully" is
crucial to this meaning), just that it's worth "less than before".

The two terms got somewhat entwined, no doubt because their spelling is
so similar (even though etimology and pronunciation are poles apart),
but the "correct" meanings and usage are still well distinct.
Alex
May 5 '07 #30
On May 4, 9:19�pm, a...@mac.com (Alex Martelli) wrote:
Larry Bates <larry.ba...@websafe.comwrote:

* *...
Isn't deprecated like depreciated but not quite to zero yet?

No. *"To deprecate" comes from a Latin verb meaning "to ward off a
disaster by prayer"; when you're saying you deprecate something, you're
saying you're praying for that something to disappear, go away; in a
secular context, you're earnestly imploring people to NOT do it.

"To depreciate" comes from a Latin verb meaning "to reduce the price";
when you're saying you depreciate something, you're saying you put on
that something a lower price (and, by extension, a lower value) than it
has (or, more commonly, used to have). *You're not necessarily saying
it's worth nothing at all (accountants sometimes deem an asset "fully
depreciated" to mean something close to that, but the adverb "fully" is
crucial to this meaning), just that it's worth "less than before".
But doesn'y "partially depreciated" also mean "less than before"?
I thought "fully depreciated" meant the value AS AN ASSET was now 0,
not the actual value, such as when my company replaces my perfectly
functioning computer because it is "fully depreciated" (the company
can
no longer extract any tax benefits from it).
>
The two terms got somewhat entwined, no doubt because their spelling is
so similar (even though etimology and pronunciation are poles apart),
but the "correct" meanings and usage are still well distinct.

Alex

May 5 '07 #31
On May 5, 12:19 pm, a...@mac.com (Alex Martelli) wrote:
Larry Bates <larry.ba...@websafe.comwrote:

...
Isn't deprecated like depreciated but not quite to zero yet?

No. "To deprecate" comes from a Latin verb meaning "to ward off a
disaster by prayer"; when you're saying you deprecate something, you're
saying you're praying for that something to disappear, go away; in a
secular context, you're earnestly imploring people to NOT do it.

"To depreciate" comes from a Latin verb meaning "to reduce the price";
when you're saying you depreciate something, you're saying you put on
that something a lower price (and, by extension, a lower value) than it
has (or, more commonly, used to have). You're not necessarily saying
it's worth nothing at all (accountants sometimes deem an asset "fully
depreciated" to mean something close to that, but the adverb "fully" is
crucial to this meaning), just that it's worth "less than before".
Seeing this thread has already deteriorated [another word with Latin
ancestry, not to be conflated with "posteriorated"] to the level of a
debate about how many angels can stand shoulder-to-shoulder between
the quotes surrounding the repr of an empty string, I presume it's OK
if I remark that a "fully depreciated" asset is one that has a *book*
value of zero [essentially that the whole of its original cost has
been written off (i.e. claimed as a tax deduction)] , and that this
has absolutely nothing to do with the true worth of the asset.

>
The two terms got somewhat entwined, no doubt because their spelling is
so similar (even though etimology and pronunciation are poles apart),
but the "correct" meanings and usage are still well distinct.

Alex

May 5 '07 #32

This thread has been closed and replies have been disabled. Please start a new discussion.

Similar topics

6
by: Ole Hanson | last post by:
Hi I am wondering if there is any programmatic difference between the String.Empty and the "" for declaring an empty string? Furthermore, is there any performance penalty by doing the one over...
8
by: monu | last post by:
hi can u write me Why string.Empty is better then "" bye
4
by: AVL | last post by:
Hi, I read that to check for empty strings , comparing strings using String.Length == 0 is faster than String.Empty or "" . Is it true...? If so, how?
9
by: Søren M. Olesen | last post by:
Hi Can someone tell me how to implement something similar to String.Empty ?? Given a class called myValue Public class myValue private id as integer private value as string end class
6
by: Charlie | last post by:
Hi: Is there any difference between string.Empty and String.Empty? And what is the benefit of using it over "". Thanks, Charlie
26
by: anonieko | last post by:
In the past I always used "" everywhere for empty string in my code without a problem. Now, do you think I should use String.Empty instead of "" (at all times) ? Let me know your thoughts.
35
by: Smithers | last post by:
I have been told that it is a good idea to *always* declare string variables with a default value of string.Empty - for cases where an initial value is not known... like this: string myString =...
21
by: Sami | last post by:
string = "" or string = string.Empty? should is the proper way? Sami
0
by: DolphinDB | last post by:
Tired of spending countless mintues downsampling your data? Look no further! In this article, you’ll learn how to efficiently downsample 6.48 billion high-frequency records to 61 million...
1
isladogs
by: isladogs | last post by:
The next Access Europe meeting will be on Wednesday 6 Mar 2024 starting at 18:00 UK time (6PM UTC) and finishing at about 19:15 (7.15PM). In this month's session, we are pleased to welcome back...
0
by: Vimpel783 | last post by:
Hello! Guys, I found this code on the Internet, but I need to modify it a little. It works well, the problem is this: Data is sent from only one cell, in this case B5, but it is necessary that data...
0
by: ArrayDB | last post by:
The error message I've encountered is; ERROR:root:Error generating model response: exception: access violation writing 0x0000000000005140, which seems to be indicative of an access violation...
1
by: PapaRatzi | last post by:
Hello, I am teaching myself MS Access forms design and Visual Basic. I've created a table to capture a list of Top 30 singles and forms to capture new entries. The final step is a form (unbound)...
1
by: CloudSolutions | last post by:
Introduction: For many beginners and individual users, requiring a credit card and email registration may pose a barrier when starting to use cloud servers. However, some cloud server providers now...
1
by: Defcon1945 | last post by:
I'm trying to learn Python using Pycharm but import shutil doesn't work
0
by: af34tf | last post by:
Hi Guys, I have a domain whose name is BytesLimited.com, and I want to sell it. Does anyone know about platforms that allow me to list my domain in auction for free. Thank you
0
by: Faith0G | last post by:
I am starting a new it consulting business and it's been a while since I setup a new website. Is wordpress still the best web based software for hosting a 5 page website? The webpages will be...

By using Bytes.com and it's services, you agree to our Privacy Policy and Terms of Use.

To disable or enable advertisements and analytics tracking please visit the manage ads & tracking page.