How can I make the if else statement as below one liner?
uly = '50'
if '-' in uly:
uly = uly.replace('-','S')
else:
uly = 'N'+uly
print uly
My trial:
uly = [uly=uly.replace('-','S') if '-' in uly else uly = 'N'+uly]
print uly
The following will do it:
uly = uly.replace('-', 'S') if '-' in uly else 'N' + uly
This uses the so-called conditional expression (similar to an if
statement except that it's an expression and not a statement).
What you have right now is an attempt at a list comprehension, which is unsuitable since there are no lists involved.
All that aside, I would urge you to rethink optimising for the shortest code. As a general rule, readability should trump compactness.
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With