Python中移除字符串前缀和后缀的方法
A few weeks ago, I learned about the removeprefix method in Python. It lets you remove a specific prefix from the beginning of a string. For example, I can use the following code to remove www. from the beginning of a domain name:
"www.jamesg.blog".removeprefix("www.")
If the string doesn’t contain the prefix, nothing happens; if the string does contain the prefix, the prefix is removed.
_Note: If you are parsing URLs in Python, you should use a library like__urllib.parse_ (https://docs.python.org/3/library/urllib.parse.html)to extract parts of a URL.
I did some digging and, via a mention of the method in Stack Overflow (https://stackoverflow.com/questions/16891340/remove-a-prefix-from-a-string), I learned that Python 3.9 added support for methods for removing prefixes and suffixes from strings (https://docs.python.org/3/whatsnew/3.9.html): removeprefix and removesuffix.
When I learned about removeprefix, I felt a little bit of joy. I have been using Python for years and had no idea about this method.
Instead of doing the trick to measure the length of a string I want to remove, and then removing that number of characters from the beginning of a string using indexing if the string startswith the string I want to remove, I now can use a single method: removeprefix (and removesuffix to do the same at the end of a string).
Addendum: lstrip and rstrip
While the lstrip() and rstrip() methods, which remove either whitespace or specified characters from the start or end of a string, may sound like they do the same thing, they remove all instances of the specified characters. For example, if I use this code:
"www.w.jamesg.blog".lstrip("www.")
The code returns:
jamesg.blog
lstrip() has removed all w and . characters that would start the string.
I thought I would document this because for a while I wasn’t aware this was the behaviour of lstrip and strip.