110

How do I make a:

if str(variable) == [contains text]:

condition?

(or something, because I am pretty sure that what I just wrote is completely wrong)

I am sort of trying to check if a random.choice from my list is ["",] (blank) or contains ["text",].

Rik Poggi
  • 28,332
  • 6
  • 65
  • 82
user1275670
  • 1,215
  • 2
  • 8
  • 9
  • do you mean `if str(variable) == "my text":` ? – Simon Bergot Mar 29 '12 at 13:36
  • You seem to be a little confused, I'd sugget you to read a [python tutorial](http://www.google.com/search?q=python+tutorial). – Rik Poggi Mar 29 '12 at 13:52
  • 3
    Possible duplicate of [Most elegant way to check if the string is empty in Python?](http://stackoverflow.com/questions/9573244/most-elegant-way-to-check-if-the-string-is-empty-in-python) – Ronak Shah Mar 03 '17 at 10:13

14 Answers14

196

You could just compare your string to the empty string:

if variable != "":
    etc.

But you can abbreviate that as follows:

if variable:
    etc.

Explanation: An if actually works by computing a value for the logical expression you give it: True or False. If you simply use a variable name (or a literal string like "hello") instead of a logical test, the rule is: An empty string counts as False, all other strings count as True. Empty lists and the number zero also count as false, and most other things count as true.

alexis
  • 48,685
  • 16
  • 101
  • 161
  • Hehe, i kind of understand the principle bout the If, True and False thingy. Warcraft 3 trigger editor: 'if (this unit equals that unit) == True' – user1275670 Apr 01 '12 at 20:28
  • I'm guessing you can leave out the `== True` part in the Warcraft editor, too. – alexis Apr 02 '12 at 11:55
  • Yep. Never actually thought of that hehe, but this is definetly helpful. – user1275670 Apr 06 '12 at 12:27
  • This is not the SAME. Do not do this. In [14]: a = "" In [15]: if a.replace(' ', ''): ...: print 1 ...: In [16]: if a.replace(' ', '') == "": ...: print 1 ...: 1 – Brett Hardin Jan 09 '17 at 21:45
  • So actually the equivalent is: `if not variable` – Andrea Bergonzo Sep 08 '17 at 14:26
  • @Brett, the examples you object to were comparing a *boolean* to `True`; yours doesn't. Of course, `""` is not equal to `False` or to `None`, but they all count as false in a logical test. When you compare a boolean, you can **always** leave out the `== True`. – alexis Sep 09 '17 at 06:08
  • 1
    Oh right, what @AndreaBergonzo said: When you compare a string to "", you're checking if it's empty-- which counts as False. – alexis Sep 26 '17 at 23:09
  • @variable, *DO NOT DO THAT*; `is` tests for object equality, and will only work as intended if all empty strings are "interred" (represented as references to the same stored object), which Python does not guarantee. (It'll probably work with Cpython, but you're relying on implementation-specific behavior.) – alexis Nov 27 '19 at 14:10
23

The "Pythonic" way to check if a string is empty is:

import random
variable = random.choice(l)
if variable:
    # got a non-empty string
else:
    # got an empty string
Community
  • 1
  • 1
Daniel Lubarov
  • 7,796
  • 1
  • 37
  • 56
17

Just say if s or if not s. As in

s = ''
if not s:
    print 'not', s

So in your specific example, if I understand it correctly...

>>> import random
>>> l = ['', 'foo', '', 'bar']
>>> def default_str(l):
...     s = random.choice(l)
...     if not s:
...         print 'default'
...     else:
...         print s
... 
>>> default_str(l)
default
>>> default_str(l)
default
>>> default_str(l)
bar
>>> default_str(l)
default
senderle
  • 145,869
  • 36
  • 209
  • 233
  • I dont get it. so, if i do "variable = random.choice(list)" and the variable is a blank "", then i can just do the condition "if variable:" and... yeah, i dont really get anything else of what you wrote... – user1275670 Mar 29 '12 at 13:37
  • @user1275670, it sounds like you do understand. But I added another example just in case. In short `''` evaluates to `False`, so if you want to get `True` when `s` is an empty string, you say `if not s`. – senderle Mar 29 '12 at 13:43
14

Empty strings are False by default:

>>> if not "":
...     print("empty")
...
empty
brice
  • 24,329
  • 7
  • 79
  • 95
8

Some time we have more spaces in between quotes, then use this approach

a = "   "
>>> bool(a)
True
>>> bool(a.strip())
False

if not a.strip():
    print("String is empty")
else:
    print("String is not empty")
kamran kausar
  • 4,117
  • 1
  • 23
  • 17
7

For python 3, you can use bool()

>>> bool(None)
False
>>> bool("")
False
>>> bool("a")
True
>>> bool("ab")
True
>>> bool("9")
True
Thai Tran
  • 9,815
  • 7
  • 43
  • 64
4
element = random.choice(myList)
if element:
    # element contains text
else:
    # element is empty ''
eumiro
  • 207,213
  • 34
  • 299
  • 261
3

How do i make an: if str(variable) == [contains text]: condition?

Perhaps the most direct way is:

if str(variable) != '':
  # ...

Note that the if not ... solutions test the opposite condition.

NPE
  • 486,780
  • 108
  • 951
  • 1,012
2

if the variable contains text then:

len(variable) != 0

of it does not

len(variable) == 0

CESCO
  • 7,305
  • 8
  • 51
  • 83
2
string = "TEST"
try:
  if str(string):
     print "good string"
except NameError:
     print "bad string"
Cornea Valentin
  • 471
  • 6
  • 12
  • 4
    Usually is a good practice in StackOverflow to comment the code posted. – King Midas May 09 '18 at 11:12
  • While this answer is probably correct and useful, it is preferred if you include some explanation along with it to explain how it helps to solve the problem. This becomes especially useful in the future, if there is a change (possibly unrelated) that causes it to stop working and users need to understand how it once worked. – Erty Seidohl May 09 '18 at 14:40
  • Sorry, my English it's so bad but in future i will keep in mind to comment my post. – Cornea Valentin May 11 '18 at 13:23
  • unfortunately I could never get to print "bad string". I tested like this `string = ""` – AhmFM Oct 27 '22 at 20:04
  • try to not set: string at all and will get the bad string result. – Cornea Valentin Nov 22 '22 at 05:13
2

use "not" in if-else

x = input()

if not x:
   print("Value is not entered")
else:
   print("Value is entered")
Megha Chovatiya
  • 483
  • 5
  • 8
2
{
test_str1 = "" 
test_str2 = "  "
  
# checking if string is empty 
print ("The zero length string without spaces is empty ? : ", end = "") 
if(len(test_str1) == 0): 
    print ("Yes") 
else : 
    print ("No") 
  
# prints No  
print ("The zero length string with just spaces is empty ? : ", end = "") 
if(len(test_str2) == 0): 
    print ("Yes") 
else : 
    print ("No") 
}
Vahid Talebi
  • 175
  • 1
  • 9
1

Python strings are immutable and hence have more complex handling when talking about its operations. Note that a string with spaces is actually an empty string but has a non-zero size. Let’s see two different methods of checking if string is empty or not: Method #1 : Using Len() Using Len() is the most generic method to check for zero-length string. Even though it ignores the fact that a string with just spaces also should be practically considered as an empty string even its non-zero.

Method #2 : Using not

Not operator can also perform the task similar to Len(), and checks for 0 length string, but same as the above, it considers the string with just spaces also to be non-empty, which should not practically be true.

Good Luck!

Vahid Talebi
  • 175
  • 1
  • 9
0
#empty variable
myvar = ""

#check if variable is empty
if not myvar:
    print("variable is empty") # variable is empty
Avnish Jayaswal
  • 161
  • 1
  • 4