質問

With the following code

import sys
print "Hello " + sys.argv[1] if len(sys.argv) > 1 else "Joe" + "."

And when I run

  • python hello.py, I get Joe. - The Hello is missing.
  • python hello.py Nick, I get Hello Nick - The period '.' in the end is missing.

However, when I change the code to cover the ternary operation with (), then it works correctly.

import sys
print "Hello " + (sys.argv[1] if len(sys.argv) > 1 else "Joe") + "."

And when I run

  • python hello.py, I get Hello Joe.
  • python hello.py Nick, I get Hello Nick.

Can someone explain why the different behavior when I don't cover ternary operator with braces.

役に立ちましたか?

解決

See the documented operator precedence; the conditional expression has the one-but-lowest precedence, only lambda is lower.

You may want to look into the string format syntax instead of manually concatenating string objects:

print "Hello {}.".format(sys.argv[1] if len(sys.argv) > 1 else "Joe")
ライセンス: CC-BY-SA帰属
所属していません StackOverflow
scroll top