3

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)
1
  • Is that =+ some cool new Python 3 thing or will that result in a TypeError? Commented May 1, 2014 at 17:55

2 Answers 2

7

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.

Sign up to request clarification or add additional context in comments.

1 Comment

You can generalize this in terms of the special methods __bool__ and __len__. It falls back on str.__len__, since str doesn't define __bool__.
1

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

1 Comment

This seems a bit contrived. If he knew what to test (empty vs non-empty string) he'd probably not be asking the question. :)

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.