Alex Rivera | Logout

How can I closely achieve ?: from C++/C# in Python?

Asked 2008-09-25T19:06:03.630
12

In C# I could easily write the following:

string stringValue = string.IsNullOrEmpty( otherString ) ? defaultString : otherString;

Is there a quick way of doing the same thing in Python or am I stuck with an 'if' statement?

Edit
Report

1 Answer

-1

You can take advantage of the fact that logical expressions return their value, and not just true or false status. For example, you can always use:

result = question and firstanswer or secondanswer

With the caveat that it doesn't work like the ternary operator if firstanswer is false. This is because question is evaluated first, assuming it's true firstanswer is returned unless firstanswer is false, so this usage fails to act like the ternary operator. If you know the values, however, there is usually no problem. An example would be:

result = choice == 7 and "Seven" or "Another Choice"
answered 2008-09-25T19:14:05.543

Your Answer