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)
Answer from Steef on Stack Overflowstrip 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)
If you are sure that the string only appears at the end, then the simplest way would be to use 'replace':
url = 'abcdc.com'
print(url.replace('.com',''))
How to remove a string suffix in Python? - TestMu AI Community
How do I remove remove stuff like (. , ' *) from a string?
help me understand why removeprefix() isn't working in this case
Pathlib is cool
Its awesome, I love the read/write_text/bytes functions so convenient!
More on reddit.com