Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

make the if else statement one liner in python

Tags:

python

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
like image 579
Taylor Avatar asked Jan 10 '23 18:01

Taylor


1 Answers

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.

like image 179
NPE Avatar answered Jan 21 '23 10:01

NPE