How to Precisely Remove Substrings from String Endings
In Python, the strip() method may not always yield the expected outcome when trying to remove substrings from string endings. This is because strip() removes characters from both ends of the string based on a specified set of characters, not an entire substring.
Python 3.9 and Newer:
For Python 3.9 and above, the preferred methods are removeprefix and removesuffix:
url = 'abcdc.com' url.removesuffix('.com') # Returns 'abcdc' url.removeprefix('abcdc.') # Returns 'com'
Python 3.8 and Older:
For earlier Python versions, you can use the following methods:
url = 'abcdc.com' if url.endswith('.com'): url = url[:-4]
import re url = 'abcdc.com' url = re.sub('\.com$', '', url)
While the removeprefix and removesuffix methods are the most concise and efficient, all these approaches provide effective ways to precisely remove substrings from string endings in Python.
The above is the detailed content of How to Precisely Remove Substring Endings from Strings in Python?. For more information, please follow other related articles on the PHP Chinese website!