Issue
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?
Solution
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('.')
Answered By - John Coleman
0 comments:
Post a Comment
Note: Only a member of this blog may post a comment.