Counting how many chars equal to a given char are in the beginning of a string

Jeff Epler jepler at unpythonic.net
Mon Dec 22 15:14:55 EST 2003


Here are several ways:

def count_initial(s, c):
    return len(s) - len(s.lstrip(c))

def count_initial(s, c):
    r = "^" + re.escape(c) + "*"
    m = re.match(r, s)
    return len(m.group(0))

# enumerate in 2.3
def count_initial(s, c):
    for i, j in enumerate(s):
        if j != c: break
    return i

# itertools in 2.3
def count_initial(s, c):
    return len(list(itertools.takewhile(lambda x: x==c, s)))

Jeff





More information about the Python-list mailing list