Home > python > Remove suffix from the right side of a text

Remove suffix from the right side of a text

Problem
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")
'pyth'

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.

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

# tip from http://stackoverflow.com/questions/1038824
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):]

Usage:

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

>>> strip_left("data/text/vmi.txt", "data/")
'text/vmi.txt'
Categories: python Tags: ,
  1. No comments yet.
  1. No trackbacks yet.

Leave a comment