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
Release: 2024-12-06 13:45:13
Original
645 people have browsed it

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

Use endswith and slicing for Python 3.8 and older:

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

Use regular expressions:

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

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!

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