Home >Backend Development >Python Tutorial >How to Remove a Suffix from a String in Python?

How to Remove a Suffix from a String in Python?

Linda Hamilton
Linda HamiltonOriginal
2024-12-06 13:45:13642browse

How to Remove a Suffix from a String in Python?

How to Remove a Substring from the String End (Remove Suffix)

To remove a substring from the end of a string, known as a suffix, there are several methods available.

Use removeprefix and removesuffix for Python 3.9 :

url = 'abcdc.com'
url.removesuffix('.com')  # Returns 'abcdc'

Use endswith and slicing for Python 3.8 and older:

if url.endswith('.com'):
    url = url[:-4]  # Remove '.com' suffix

Use regular expressions:

import re
url = re.sub('\.com$', '', url)  # Remove '.com' suffix

Note that the strip() method does not remove entire substrings but only strips individual characters specified in the argument.

The above is the detailed content of How to Remove a Suffix from a String 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