Python 在if语句中使用字符串
如果以下代码中的word:,有人能解释一下在语句Python 在if语句中使用字符串,python,if-statement,python-3.x,Python,If Statement,Python 3.x,如果以下代码中的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:
中对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中的非空字符串始终为True,否则为False。因此,如果word仍然是空字符串,那么它将为False,否则为True。为什么不在Python的REPL中亲自尝试它(这是该语言及其类语言的优点之一):
这似乎有点做作。如果他知道测试什么(空字符串与非空字符串),他可能不会问这个问题。:)这是=+
一些很酷的新Python 3东西,还是会导致类型错误
?您可以用特殊的方法和方法来概括这一点。由于str
没有定义\uuuuu bool\uuuu
,因此它依赖于str.\uuuu len\uuuuu
。
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