Thursday, February 29, 2024
HomeSoftware EngineeringTips on how to Take away Trailing Zeroes in Python

Tips on how to Take away Trailing Zeroes in Python


The problem

Numbers ending with zeros are boring.

They could be enjoyable in your world, however not right here.

Eliminate them. Solely the ending ones.

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

The answer in Python code

Possibility 1:

def no_boring_zeros(n):
    n = str(n)
    for i in vary(len(n)-1, 0, -1):
        if n[i]=="0":
            n = n[:-1:]
        else:
            return int(n)
    return int(n)

Possibility 2:

def no_boring_zeros(n):
    attempt:
        return int(str(n).rstrip('0'))
    besides ValueError:
        return 0

Possibility 3:

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

Take a look at instances to validate our answer

import take a look at
from answer import no_boring_zeros

@take a look at.describe("Mounted Checks")
def fixed_tests():
    @take a look at.it('Primary Take a look at Instances')
    def basic_test_cases():
        take a look at.assert_equals(no_boring_zeros(1450), 145)
        take a look at.assert_equals(no_boring_zeros(960000), 96)
        take a look at.assert_equals(no_boring_zeros(1050), 105)
        take a look at.assert_equals(no_boring_zeros(-1050), -105)
        take a look at.assert_equals(no_boring_zeros(0), 0)
        take a look at.assert_equals(no_boring_zeros(2016), 2016)
RELATED ARTICLES

LEAVE A REPLY

Please enter your comment!
Please enter your name here

Most Popular

Recent Comments