2017-05-04 39 views
0

使用三元操作for循環當我在Python 3測試三元運算符,我碰到這種怪異的現象怪異的行爲,而在Python 3.5

import string 
test = "" 
testing = chr(0) if chr(0) in test else "" 
for c in string.ascii_letters + testing: 
    print(c) 

來將打印每行A〜Z 1個字符,但

import string 

test = "" 
for c in string.ascii_letters + chr(0) if chr(0) in test else "": 
    print(c) 

不會打印任何東西。
有人可以給我一個解釋嗎?

+3

在string.ascii_letters +中更改爲'for c +(chr(0)if chr(0)in test else「」)'並且它將起作用。 – Maroun

+0

有沒有Python字符串包含NUL字符的情況或平臺? – Evert

+3

檢查運算符優先順序:https://docs.python.org/3/reference/expressions.html#operator-precedence – falsetru

回答

0

這是由於運算符優先級:+結合比if更緊。

在第一個片段中,testing評估爲「」,因爲chr(0)不在test中。所以,循環結束了ascii_letters +「」,即只是字母。

第二,首先評估+;因此if將整個事件評估爲"",並且該循環剛好位於空字符串之上。

0

更改爲:

for c in string.ascii_letters + (chr(0) if chr(0) in test else ""): 

,它會工作。

爲什麼? Operator precedence。您當前的代碼實際上是:

for c in (string.ascii_letters + chr(0)) if chr(0) in test else "":