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
Release: 2024-12-03 07:31:09
Original
386 people have browsed it

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'
Copy after login

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]
Copy after login
  • Regular Expression:
import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)
Copy after login

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!

source:php.cn
Statement of this Website
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
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template