Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

Is it possible to place break in python one liner ternary conditional operator

I want to break the loop in else part of python one liner.

value='4,111,010.00400'
for i in value[-1:value.rfind('.')-1:-1]:
    if i in ('0', '.'):
        value=value[:-1]
    else:
        break

I wrote this code and trying to convert it to python one liner. So wrote like this

for i in value[-1:value.rfind('.')-1:-1]:
    value=value[:-1] if i in ('0', '.') else break

But not able to place break inside that one liner. Is it any alternative way to place it or is it possible to achieve the above in python oneliner?

like image 562
Vanjith Avatar asked Sep 18 '25 01:09

Vanjith


1 Answers

As you have discovered, you can't use break with the ternary operator for the simple reason that break isn't a value. Furthermore, while if statements with no else can be put onto one line, the else prevents a nice 1-line solution.

Your code strips away trailing 0 and at most one period (if everything after that period is 0). It is thus equivalent to:

value = value.rstrip('0').rstrip('.')
like image 60
John Coleman Avatar answered Sep 19 '25 16:09

John Coleman