Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

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

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?

like image 871
Jordan Parmer Avatar asked Sep 25 '08 19:09

Jordan Parmer


1 Answers

In Python 2.5, there is

A if C else B

which behaves a lot like ?: in C. However, it's frowned upon for two reasons: readability, and the fact that there's usually a simpler way to approach the problem. For instance, in your case:

stringValue = otherString or defaultString
like image 152
Thomas Wouters Avatar answered Oct 14 '22 23:10

Thomas Wouters