Reputation: 161
I'm curious if something like this is possible:
print "lajsdflk"+ (if x>1:"123123";else:"0000000") +"!@#"
Not specifically printing but just any function with numbers; another example:
print 596* (if statementX: 6545; else: 9874) /63
If possible I'd like to keep it to one line.
Upvotes: 2
Views: 178
Reputation: 239523
You can use conditional expression, like this
>>> "lajsdflk" + ("123123" if 5 > 1 else "0000000") + "!@#"
'lajsdflk123123!@#'
>>> "lajsdflk" + ("123123" if 0 > 1 else "0000000") + "!@#"
'lajsdflk0000000!@#'
Since Python accepts any Truthy value in the if
's expression, you can even use any function, like this
>>> "lajsdflk" + ("123123" if "abcd1234".isalnum() else "0000000") + "!@#"
'lajsdflk123123!@#'
There is another trick people use. It goes like this
>>> "lajsdflk" + ("0000000", "123123")[5 > 1] + "!@#"
'lajsdflk123123!@#'
>>> "lajsdflk" + ("0000000", "123123")[0 > 1] + "!@#"
'lajsdflk0000000!@#'
Here, a tuple is prepared with the possible outcomes and based on the result of the comparison operation, the possible value is chosen. Here, 5 > 1
is evaluated and found out to be Truthy and since Python's True
equals 1 and False
equals 0
, 5 > 1
evaluates to be 1.
>>> 0 == False
True
>>> 1 == True
True
Note: This trick has a problem. Consider this case,
>>> 1 + (2, 3/0)[4 > 0] + 5
Traceback (most recent call last):
File "<input>", line 1, in <module>
ZeroDivisionError: integer division or modulo by zero
Because, when the tuple is created all the values are evaluated and Python cannot divide 1
by 0
. But, this problem will not be there with conditional expression,
>>> 1 + (2 if 4 > 0 else 3/0) + 5
8
Because it evaluates the values only if the branch is hit.
Upvotes: 5