0

While I was testing ternary operator in python 3, I came across this weird phenomenon

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

would print a~Z 1 character per line, but

import string

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

would print nothing.
Can somebody give me an explanation?

5
  • 3
    Change to for c in string.ascii_letters + (chr(0) if chr(0) in test else "") and it will work. Commented May 4, 2017 at 8:22
  • Are there cases or platforms where a Python string contains a NUL character? Commented May 4, 2017 at 8:23
  • 3
    Check operator precedence: docs.python.org/3/reference/… Commented May 4, 2017 at 8:23
  • 1
    operator precedence. When you have a doubt, use parentheses. Commented May 4, 2017 at 8:23
  • why is the variable test or the if statement being used? as just doing this for c in string.ascii_letters: print(c) gives the same functionality Commented May 4, 2017 at 8:27

2 Answers 2

0

This is due to operator precedence: + binds tighter than if.

In the first snippet, testing evalutes to "" because chr(0) is not in test. So, the loop is over ascii_letters + "", ie just the letters.

In the second, the + is evaluated first; the if therefore evaluates the whole thing to "" and the loop is just over the empty string.

Sign up to request clarification or add additional context in comments.

Comments

0

Change to:

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

and it will work.

Why? Operator precedence. Your current code is actually:

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

Comments

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.