18

I am trying to write a function that returns the number of trailing 0s in a string or integer. Here is what I am trying and it is not returning the correct values.

def trailing_zeros(longint):
    manipulandum = str(longint)
    x = 0
    i = 1
    for ch in manipulandum:
        if manipulandum[-i] == '0':
            x += x
            i += 1
        else:
            return x
Dharman
  • 30,962
  • 25
  • 85
  • 135
  • "not returning the correct values"? It helps if you provide the test cases you are using with the expected answers and the answers you are getting. – S.Lott Dec 21 '11 at 16:52
  • I guess you meant to say `i += 1`. – Paul Manta Dec 21 '11 at 16:52
  • "thanks for the input". Not really helpful. You should actually **update** your question with inputs, actual outputs and expected outputs. Merely agreeing that it's a good idea doesn't help anyone learn from your question. Actually **update** it, please. And. Don't write "status" comments. "Yes, I did" and "New to this site" don't clarify the question in any way. Please remove them. – S.Lott Dec 21 '11 at 21:05

10 Answers10

36

For strings, it is probably the easiest to use rstrip():

In [2]: s = '23989800000'

In [3]: len(s) - len(s.rstrip('0'))
Out[3]: 5
NPE
  • 486,780
  • 108
  • 951
  • 1,012
20

May be you can try doing this. This may be easier than counting each trailing '0's

def trailing_zeros(longint):
    manipulandum = str(longint)
    return len(manipulandum)-len(manipulandum.rstrip('0'))
Abhijit
  • 62,056
  • 18
  • 131
  • 204
3

String-Methods a quite clearly answered - here is one with keeping the integer. You can get it also with using modulo (%) with 10 in the loop, and then reduce your given number by dividing it by then in the next loop:

    def end_zeros(num: int):
        n = 0
        while num%10 == 0:
            n += 1
            num = num/10
            return n
        else:
            return 0

Without defining num as integer:

    def end_zeros(num):
        if num == 0:
            return 1
        elif num%10 == 0:
            n = 0
            while num%10 == 0:
                n += 1
                num = num/10
            return n
        else:
            return 0
Cabista
  • 31
  • 2
2

Here are two examples of doing it:

  1. Using rstrip and walrus := operator. Please notice that it only works in Python 3.8 and above.

def end_zeros(num):
    return len(s := str(num)) - len(s.rstrip("0"))
  1. Using findall() regular expression (re) function:

from re import findall
    
def end_zeros(num):
    return len(findall("0*$", str(num))[0])
Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
2

You can use bitwise operators:

>>> def trailing_zeros(x):
...     return (x & -x).bit_length() - 1
... 
>>> trailing_zeros(0b0110110000)
4
>>> trailing_zeros(0b0)
-1
Be3y4uu_K0T
  • 318
  • 4
  • 10
1

if you want to count how many zeros at the end of your int:

   def end_zeros(num):
        new_num = str(num)
        count = len(new_num) - len(new_num.rstrip("0"))
        return count



    print(end_zeros(0))  # == 1
    print(end_zeros(1))  # == 0
    print(end_zeros(10))  # == 1
    print(end_zeros(101))  # == 0
    print(end_zeros(245))  # == 0
    print(end_zeros(100100))  # == 2
Kasem777
  • 737
  • 7
  • 10
1

You could just:

  1. Take the length of the string value of what you're checking
  2. Trim off trailing zeros from a copy of the string
  3. Take the length again, of the trimmed string
  4. Subtract the new length from the old length to get the number of zeroes trailing.
Sheridan Bulger
  • 1,214
  • 7
  • 9
0

I found two ways to achieve this, one is already mentioned above and the other is almost similar:

manipulandum.count('0') - manipulandum.rstrip('0').count('0')

But still, I'm looking for some better answer.

Shadow The GPT Wizard
  • 66,030
  • 26
  • 140
  • 208
0

The question asks to count the trailing zeros in a string or integer. For a string, len(s) - len(s.rstrip('0')) is fine. But for an integer, presumably you don't want to convert it to a string first. In that case, use recursion:

def trailing_zeros(longint):
    assert(longint)
    return ~longint % 2 and trailing_zeros(longint/2) + 1
personal_cloud
  • 3,943
  • 3
  • 28
  • 38
  • Your answer appears to be correct for base 2, but everyone else on this question is working in base 10. Consider instead answering https://stackoverflow.com/questions/40608220/pythonic-way-to-count-the-number-of-trailing-zeros – o11c Aug 23 '20 at 20:34
0

Here are two examples of doing it:

  1. Using rstrip and walrus := operator. Please notice that it only works in Python 3.8 and above.

    def end_zeros(num): return len(s := str(num)) - len(s.rstrip("0"))

  2. Using re.findall() function:

    from re import findall

    def end_zeros(num): return len(findall("0*$", str(num))[0])

Vlad Bezden
  • 83,883
  • 25
  • 248
  • 179
  • 2
    This is a duplicate post; your other answer has better formatting so please delete this one. – o11c Aug 23 '20 at 19:03