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 slice a string from the end
python - Slice to the end of a string without using len() - Stack Overflow
How to extract last three characters of a string?
how to get what index position the last character of a string is
Videos
hi, i'm playing with string slice and i don't understand some things. i know that the [-1] is the last charachter, [-2] the penultimate etc. so, i have a string like "file.txt" and i want to exctract only the ".txt" part of it. i tried with string[-1:-4] but i get an empty string; then i tried with string[:len(string)-5:-1] but i get "txt.". i don't know what i'm doing wrong, can someone explain it to me? thank you
I can't for the life of me find any documentation on how to do this so I apologize.
In python its
string = "D:\\nim\\nim.zip" print(string[-4:])
This outputs .zip. I can see in Nim how to slice a string from the start (0 .. ^4) but not backwards. Is this possible without writing a huge function?