【问题标题】:Using a string in if statement在 if 语句中使用字符串
【发布时间】:2014-06-18 06:20:01
【问题描述】:

谁能在下面的代码中的if word: 语句中解释对word 执行的检查?

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)

【问题讨论】:

  • =+ 是不是一些很酷的新 Python 3 东西,还是会导致 TypeError

标签: python if-statement python-3.x


【解决方案1】:

为什么不在 Python 的 REPL 中亲自尝试一下(这是该语言和同类语言的优点之一):

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

【讨论】:

  • 这似乎有点做作。如果他知道要测试什么(空字符串与非空字符串),他可能不会问这个问题。 :)
【解决方案2】:

python 中的非空字符串始终为 True,否则为 False。因此,如果 word 仍然是您的空字符串,它将为 False,否则为 True。

【讨论】:

  • 您可以根据__bool____len__ 的特殊方法来概括这一点。它依赖于str.__len__,因为str 没有定义__bool__
猜你喜欢
  • 2013-12-13
  • 1970-01-01
  • 2014-03-02
  • 2018-08-09
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多