How Can I Efficiently Remove a Substring from the End of a String?
Problem:
Given a string like "abcdc.com", we want to remove the ".com" suffix. However, using strip('.com') leaves us with "abcd" instead of the desired "abcdc".
Python 3.9 Solution:
Python 3.9 introduced the removesuffix method, which cleanly removes specified substrings from the end of a string:
url = 'abcdc.com' url.removesuffix('.com') # Outputs: 'abcdc'
Python 3.8 and Older Solutions:
In earlier Python versions, several alternative methods exist:
url = 'abcdc.com' if url.endswith('.com'): url = url[:-4] # Remove four characters from the end
import re url = 'abcdc.com' url = re.sub('\.com$', '', url)
Considerations:
The above is the detailed content of How Can I Efficiently Remove a String Suffix in Python?. For more information, please follow other related articles on the PHP Chinese website!