Home > Backend Development > Python Tutorial > How Can I Efficiently Remove a String Suffix in Python?

How Can I Efficiently Remove a String Suffix in Python?

DDD
Release: 2024-11-30 08:42:12
Original
879 people have browsed it

How Can I Efficiently Remove a String Suffix in Python?

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

Python 3.8 and Older Solutions:

In earlier Python versions, several alternative methods exist:

  • endswith and Slicing: Check if the string ends with ".com" and slice it off if necessary:
url = 'abcdc.com'
if url.endswith('.com'):
    url = url[:-4]  # Remove four characters from the end
Copy after login
  • Regular Expression: Use a regular expression to search and replace the ".com" suffix:
import re
url = 'abcdc.com'
url = re.sub('\.com$', '', url)
Copy after login

Considerations:

  • strip strips any character in the specified set from the beginning or end of the string.
  • removesuffix only removes the specified suffix from the end of the string.
  • re.sub can search and replace any specified substring, but it can be more complex for simple replacements.

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!

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
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template