#!/usr/bin/env python
# -*- coding: utf-8 -*-
import re

def lreplace(s, old, new):
    """Return a copy of string `s` with leading occurrences of
    substring `old` replaced by `new`.

    >>> lreplace('abcabcdefabc', 'abc', 'X')
    'XXdefabc'
    >>> lreplace('_abc', 'abc', 'X')
    '_abc'
    >>> print lreplace('☃☃_[☃]_☃', '☃', 'SM')
    SMSM_[☃]_☃
    """
    return re.sub(r'^(?:%s)+' % re.escape(old),
                  lambda m: new * (m.end() // len(old)),
                  s)

def replaceLeadingString(string, old, new = ''):
    # http://stackoverflow.com/q/4649997
    n = 0
    o = 0
    s = len(old)

    while string.startswith(old, o):
        n += 1
        o += s

    return new * n + string[o:]

#from profilestats import profile
#@profile
def test(n):
    for _ in xrange(n):
        old, new = 'префикс', 'abc'
        for s in [old*2 +'остаток',
                  'no'+old,
                  old,
                  old*2,
                  new+new,
                  'xx\n'+old,
                  ]:
            args = s, old, new
            assert lreplace(*args) == replaceLeadingString(*args)
    
if __name__=="__main__":
    import cProfile
    cProfile.run('test(10**4)')

