How to Remove Trailing Zeroes in Python

The challenge

Numbers ending with zeros are boring.

They might be fun in your world, but not here.

Get rid of them. Only the ending ones.

1450 -> 145 960000 -> 96 1050 -> 105 -1050 -> -105

The solution in Python code

Option 1:

def no_boring_zeros(n): n = str(n) for i in range(len(n)-1, 0, -1): if n[i]=="0": n = n[:-1:] else: return int(n) return int(n)
Code language: Python (python)

Option 2:

def no_boring_zeros(n): try: return int(str(n).rstrip('0')) except ValueError: return 0
Code language: Python (python)

Option 3:

def no_boring_zeros(n): return int(str(n).rstrip("0")) if n else n
Code language: Python (python)

Test cases to validate our solution

import test from solution import no_boring_zeros @test.describe("Fixed Tests") def fixed_tests(): @test.it('Basic Test Cases') def basic_test_cases(): test.assert_equals(no_boring_zeros(1450), 145) test.assert_equals(no_boring_zeros(960000), 96) test.assert_equals(no_boring_zeros(1050), 105) test.assert_equals(no_boring_zeros(-1050), -105) test.assert_equals(no_boring_zeros(0), 0) test.assert_equals(no_boring_zeros(2016), 2016)
Code language: Python (python)
Tags:
Subscribe
Notify of
guest
0 Comments
Inline Feedbacks
View all comments