nicer way to remove prefix of a string if it exists

Paul McGuire ptmcg at austin.rr.com
Wed Jul 14 09:40:58 EDT 2010


On Jul 13, 6:49 pm, News123 <news1... at free.fr> wrote:
> I wondered about a potentially nicer way of removing a prefix of a
> string if it exists.
>

Here is an iterator solution:

from itertools import izip

def trim_prefix(prefix, s):
    i1,i2 = iter(prefix),iter(s)
    if all(c1==c2 for c1,c2 in izip(i1,i2)):
        return ''.join(i2)
    return s

print trim_prefix("ABC","ABCDEFGHI")
print trim_prefix("ABC","SLFJSLKFSLJFLSDF")


Prints:

DEFGHI
SLFJSLKFSLJFLSDF


-- Paul



More information about the Python-list mailing list