How to Remove Trailing Zeroes in Python

0 min read 120 words

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)

Option 2:

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

Option 3:

def no_boring_zeros(n):
  return int(str(n).rstrip("0")) if n else n

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)
Tags:
Andrew
Andrew

Andrew is a visionary software engineer and DevOps expert with a proven track record of delivering cutting-edge solutions that drive innovation at Ataiva.com. As a leader on numerous high-profile projects, Andrew brings his exceptional technical expertise and collaborative leadership skills to the table, fostering a culture of agility and excellence within the team. With a passion for architecting scalable systems, automating workflows, and empowering teams, Andrew is a sought-after authority in the field of software development and DevOps.

Tags