如何在Python的if语句中换行而不出现语法错误?
假设你在Python中有一个这样的if语句:
if not "string1" in item and not "string2" in item and not "string3" in item and not "string4" in item:
doSomething(item)
有没有办法把这个if语句分成多行呢?像这样:
if not "string1" in item
and not "string2" in item
and not "string3 in item
and not "string4" in item:
doSomething(item)
这样做可以吗?有没有其他更“符合Python风格”的方法,让它看起来更容易读呢?
6 个回答
2
反斜杠看起来很难看。如果你不想要换行了,就得把反斜杠去掉。不过如果你加上括号,就不用改什么了。
另外,在这种情况下你可能还想考虑:
if not ("string1" in item
or "string2" in item
or "string3" in item
or "string4" in item):
doSomething(item)
2
没错,只需要在换行符前面加一个反斜杠就可以了:
if not "string1" in item \
and not "string2" in item \
and not "string3 in item \
and not "string4" in item:
doSomething(item)
7
一般来说,当你想把一个表达式分成多行时,可以使用括号:
if (not "string1" in item
and not "string2" in item
and not "string3" in item
and not "string4" in item):
doSomething(item)
这个建议直接来自于Python的风格指南(PEP 8):
处理长行的推荐方法是使用Python在括号、方括号和大括号内的隐式换行。长行可以通过把表达式放在括号里来分成多行。
但要注意,在这种情况下,你还有更好的选择:
if not any(s in item for s in ("string1", "string2", "string3", "string4")):
doSomething(item)