Let's talk about how to check for prefixes and suffixes on Python's strings.
Slicing works, but there's a better way
We have a couple strings and we'd like to check whether one string is a prefix of another:
>>> filename = "report_housing_2030.pdf"
>>> prefix = "report_"
We could do that by getting the length of the prefix string and then slicing the other string to get the same prefix from it, and then comparing those strings to see whether they're equal:
>>> filename[:len(prefix)] == prefix
True
If we wanted to check whether one string was a suffix of another, we could do the same thing using negative indexes and slicing from the end of the string:
>>> tag = "app:v2.1.0-alpine"
>>> suffix = "-alpine"
>>> tag[-len(suffix):] == suffix
True
This all works, but this code is more awkward than it needs to be.
The startswith and endswith methods
Strings in Python have a startswith method that will check whether a given string is a prefix of our string:
>>> filename.startswith(prefix)
True
Strings also have an endswith method that will check whether one string is a suffix of another:
>>> tag.endswith(suffix)
True
I find the startswith and endswith methods a lot more readable than the equivalent slicing code.
Checking for multiple string prefixes/suffixes
The startswith method accepts strings, but it can also accept a tuple of strings:
>>> log_line = "[WARNING] Low memory"
>>> log_line.startswith(("[ERROR]", "[WARNING]", "[INFO]"))
True
When a tuple is passed to startswith, it will check whether any of the strings within the tuple are prefixes.
The endswith method also supports either a string, for a single suffix, or a tuple of strings, for multiple possible suffixes:
>>> flag = "run-code-beta"
>>> flag.endswith(("-beta", "-alpha", "-experimental"))
True
Removing a string prefix or a suffix in Python
What if we need to remove a possible prefix or suffix?
For example, what if we wanted to remove the mailto: prefix from a string?
>>> mailto = "mailto:"
>>> email = "mailto:[email protected]"
Well, we could pair startswith (or endswith) with string slicing.
>>> if email.startswith(mailto):
... email = email[len(mailto):]
...
>>> email
'[email protected]'
This works. But again, there's a better way.
Strings also have a removeprefix method, which basically does exactly that:
>>> email = email.removeprefix(mailto)
>>> email
'[email protected]'
If the prefix is found, a new string is returned with the prefix removed. If the prefix isn't found, the original string is returned.
The removesuffix method works the same, but for a possible suffix at the end of the string:
>>> name = "fix-footer-staging"
>>> name.removesuffix("-staging")
'fix-footer'
Note that while startswith and endswith methods can accept a tuple to check for multiple possible prefixes or suffixes, the removeprefix and removesuffix methods only accept strings... so they can only remove one prefix or suffix at a time.
How is this different from the strip method?
If you've seen the various string strip methods, you might be wondering, how are removeprefix and removesuffix any different from lstrip and rstrip?
Well, lstrip accepts any number of characters and it returns a new string with all occurrences of any of those characters removed from the beginning of the string:
>>> header = "### Testing Process"
>>> header.lstrip("# ")
'Testing Process'
Unlike removeprefix, lstrip works with individual characters.
Also, lstrip removes all leading characters that match, while removeprefix removes just the first prefix.
>>> header.removeprefix("#")
'## Testing Process'
So removeprefix removes just one occurrence of a leading substring, while lstrip removes all occurrences of specific leading characters.
The rstrip method does the same thing as lstrip but for the end of a string and the strip method removes matching characters from both sides of a string.
So if you're actually trying to remove any number of repetitions of a specific character from either end of a string, you probably want one of the strip methods.
Finding and removing string prefixes and suffixes
To check for a prefix or suffix, use the string startswith or endswith methods.
To remove a prefix or suffix, use the removeprefix or removesuffix methods.
If you need to remove repeated characters from either end of a string, check out the various strip methods instead.
For more on Python's many string methods, see Python's string methods.
Remember this next month 🧠
Now make sure you remember what you just watched: Daily Recall shows you a few Python questions a day and brings each one back right before you’d forget it.
Need a multi-line string but don't want to include a big block of manually dedented text in your Python code? Use textwrap.dedent!