Thursday, April 16, 2009

Count total repeated trailing characters in python

In a string like "243242400031230000" , find the total number of consecutive zero's (0) which are at the end.

Python solution:
The difference of length of the string and the length of the string with trailing 0's removed will give us the total number of successive trailing 0's in the string.

$ python
>>> s="243242400031230000"
>>> len(s) - len(s.rstrip("0"))

Related functions and concepts:

str.rstrip([chars]) : It return a copy of the string with trailing characters removed. Read more here

len() : This built-in function returns the length of a string