In Python, how do I count trailing zeros in a string or integer?

I am trying to write a function that returns the number of trailing 0s in a string or an integer. This 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 
+6
source share
4 answers

Maybe you can try to do it. It could be easier than counting each end "0"

 def trailing_zeros(longint): manipulandum = str(longint) return len(manipulandum)-len(manipulandum.rstrip('0')) 
+8
source

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

 In [2]: s = '23989800000' In [3]: len(s) - len(s.rstrip('0')) Out[3]: 5 
+20
source

You could simply:

  • Take the length of the string value of what you are checking.
  • Trim trailing zeros from string copy
  • Take the length again, the cropped string
  • Subtract the new length from the old length to get the number of zeros ending in.
+1
source

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

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

But still I'm looking for a better answer.

0
source

Source: https://habr.com/ru/post/904260/


All Articles