0

I'm an inexperienced programmer. I'm trying to remove trailing zeros from a whole number, an integer, for a project I've set myself in python.

I have managed to do this but there must be a better way than the monstrosity I have concocted!

def removeZeros(number):
    return int(str(int(str(number)[::-1]))[::-1])

Essentially I'm turning the integer into a string, reversing the string, turning it back into an integer---which removes the now leading zeros, turning it back into a string and reversing it; and finally turning it back into an integer to return it.

Any help would be appreciated.

Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
sylph
  • 125
  • 2
  • 9
  • You may want to look into the differences between floats and integers, that may help you get in the right direction. – miike3459 Oct 20 '18 at 16:59
  • 1
    What about `int(str(number).strip("0"))`? – guidot Oct 20 '18 at 17:00
  • 1
    Possible duplicate of [How to remove leading and trailing zeros in a string? Python](https://stackoverflow.com/questions/13142347/how-to-remove-leading-and-trailing-zeros-in-a-string-python) – Syed Faizan Oct 20 '18 at 17:02
  • are you sure that you want to remove trailing zero's from `integer`? not float? – BladeMight Oct 20 '18 at 17:02
  • @guidot thats the one, thanks. – sylph Oct 20 '18 at 17:52
  • @BladeMight I definitely need integer, I'm storing the results as integer in sqlite and will calculate the value in money in python. The trailing zeros are the result of a calculation but are not needed. – sylph Oct 20 '18 at 17:55

1 Answers1

7

Just use str.rstrip():

def remove_zeros(number):
    return int(str(number).rstrip('0'))

You could also do it without converting the number to a string, which should be slightly faster:

def remove_zeros(number):
    while number % 10 == 0:
        number //= 10
    return number
Eugene Yarmash
  • 142,882
  • 41
  • 325
  • 378
  • can you explain what is happening in your second example? – sylph Oct 20 '18 at 18:02
  • @sylph While the last digit of the number is `0` (checked with the [`%`](https://stackoverflow.com/q/4432208/244297) operator) we discard it by dividing the number by 10. – Eugene Yarmash Oct 20 '18 at 18:06
  • Thanks I just worked it out. I keep forgetting you can do `x //= 10` instead of `x = x / 10`. Need to do more studying! Very elegant solution by the way and perfect for what I need, thanks. – sylph Oct 20 '18 at 18:10
  • Just a quick note about @EugeneYarmash's comment: the operator `%` doesn't check what the last digit of a number is. It just computes the remainder of a division ie. `13 % 10` gives you `3` because `13 / 10 = 1 remainder 3`. It's just that in base 10, if a number is divisible by 10 then it ends with a `0`. – math2001 Oct 09 '19 at 02:45