Vanjith
Vanjith

Reputation: 540

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?

Upvotes: 4

Views: 2002

Answers (1)

John Coleman
John Coleman

Reputation: 52008

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('.')

Upvotes: 5

Related Questions