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.
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'))
You could just:
Here are two examples of doing it:
def end_zeros(num):
return len(s := str(num)) - len(s.rstrip("0"))
from re import findall
def end_zeros(num):
return len(findall("0*$", str(num))[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
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
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.