Posts Tagged ‘lstrip’

Remove suffix from the right side of a text

August 2, 2013 Leave a comment

You have a string and you want to remove a substring from its right side. Your first idea is “rstrip“, but when you try it out, you get a strange result:

>>> "python.json".rstrip(".json")

Well, it’s not surprising if you know how “rstrip” works. Here the string “.json” is a set of characters, and these characters are removed from the right side of the original string. It goes from right to left: “n” is in the set, remove; remove “o“, remove “s“, remove “j“, remove “.“, then go on: “n” is in the set, remove; “o” is in the set, remove; “h” is not in the set, stop.

If you want to remove a suffix from a string, try this:

# tip from
def strip_right(text, suffix):
    if not text.endswith(suffix):
        return text
    # else
    return text[:len(text)-len(suffix)]

Note that you cannot simply write “return text[:-len(suffix)]” because the suffix may be empty too.

How to remove a prefix:

def strip_left(text, prefix):
    if not text.startswith(prefix):
        return text
    # else
    return text[len(prefix):]


>>> strip_right("python.json", ".json")

>>> strip_left("data/text/vmi.txt", "data/")
Categories: python Tags: ,