Logo Questions Linux Laravel Mysql Ubuntu Git Menu
 

How do I remove a substring from the end of a string?

Tags:

python

string

I have the following code:

url = 'abcdc.com' print(url.strip('.com')) 

I expected: abcdc

I got: abcd

Now I do

url.rsplit('.com', 1) 

Is there a better way?

like image 721
Ramya Avatar asked Jun 24 '09 14:06

Ramya


People also ask

How do I remove a string from the end of a string in Python?

Use the . rstrip() method to remove whitespace and characters only from the end of a string.

How do I remove a specific part of a string in Java?

The first and most commonly used method to remove/replace any substring is the replace() method of Java String class. The first parameter is the substring to be replaced, and the second parameter is the new substring to replace the first parameter.


1 Answers

strip doesn't mean "remove this substring". x.strip(y) treats y as a set of characters and strips any characters in that set from both ends of x.

On Python 3.9 and newer you can use the removeprefix and removesuffix methods to remove an entire substring from either side of the string:

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

The relevant Python Enhancement Proposal is PEP-616.

On Python 3.8 and older you can use endswith and slicing:

url = 'abcdc.com' if url.endswith('.com'):     url = url[:-4] 

Or a regular expression:

import re url = 'abcdc.com' url = re.sub('\.com$', '', url) 
like image 98
Steef Avatar answered Sep 29 '22 12:09

Steef