Home >Backend Development >Python Tutorial >How to Precisely Remove Substring Endings from Strings in Python?

How to Precisely Remove Substring Endings from Strings in Python?

Patricia Arquette
Patricia ArquetteOriginal
2024-12-03 07:31:09451browse

How to Precisely Remove Substring Endings from Strings in Python?

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:

  • endswith() and Slicing:
url = 'abcdc.com'
if url.endswith('.com'):
    url = url[:-4]
  • Regular Expression:
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!

Statement:
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn