Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Using a string in if statement

Can anyone explain what check is being performed on word in the statement if word: in the following code?

def simplify(text, space=" \t\n\r\f", delete=""):
    result = []
    word = ""
    for char in text:
        if char in delete:
            continue
        elif char in space:
            if word:
                result.append(word)
                word = ""
        else:
            word += char
    if word:
        result.append(word)
    return " ".join(result)
like image 541
Ejaz Avatar asked Aug 03 '26 14:08

Ejaz


2 Answers

A non empty string in python is always True, otherwise False. So if word is still your empty string it will be False, otherwise True.

like image 170
ZekeDroid Avatar answered Aug 05 '26 10:08

ZekeDroid


Why not try it for yourself in Python's REPL (that's one of the beauty of the language and languages in its class):

Python 2.7.6 (default, Mar 22 2014, 22:59:56) 
[GCC 4.8.2] on linux2
Type "help", "copyright", "credits" or "license" for more information.
>>> word = ""
>>> if word: print "I'm here"
... 
>>> word = "not empty"
>>> if word: print "I'm here"
... 
I'm here
like image 33
Santa Avatar answered Aug 05 '26 10:08

Santa



Donate For Us

If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!