如何在Python三元运算符上换行?
发布于 2021-01-29 15:16:52
有时在Python中包含三元运算符的行会变得太长:
answer = 'Ten for that? You must be mad!' if does_not_haggle(brian) else "It's worth ten if it's worth a shekel."
是否建议使用三元运算符在79个字符处换行?我在PEP
8中找不到它。
关注者
0
被浏览
162
1 个回答
-
answer = ( 'Ten for that? You must be mad!' if does_not_haggle(brian) else "It's worth ten if it's worth a shekel.")
这称为隐式线连接。
上面使用PEP8一切缩进一步的样式(称为悬挂缩进)。您也可以缩进多余的行以匹配左括号:
answer = ('Ten for that? You must be mad!' if does_not_haggle(brian) else "It's worth ten if it's worth a shekel.")
但这会使您更快地达到80列的最大值。
您将
if
和放在哪个位置完全else
取决于您;我在上面使用了我的个人喜好,但是对于操作员,尚没有任何人同意的特定样式。