To remove everything after the first occurrence of the character '-' in a string, pass the character '-' as a separator in the partition() function. Then assign the part before the separator to the original string variable. It will affect that we have deleted everything after the character '-' in a string.
Using 'str. replace() , we can replace a specific character. If we want to remove that specific character, replace that character with an empty string. The str. replace() method will replace all occurrences of the specific character mentioned.
lstrip() #strips everything before and including the character or set of characters you say. If left blank, deletes whitespace.. rstrip() #strips everything out from the end up to and including the character or set of characters you give. If left blank, deletes whitespace at the end.
Python String | split()split() method in Python split a string into a list of strings after breaking the given string by the specified separator. Parameters : separator : This is a delimiter. The string splits at this specified separator.
Split on your separator at most once, and take the first piece:
sep = '...'
stripped = text.split(sep, 1)[0]
You didn't say what should happen if the separator isn't present. Both this and Alex's solution will return the entire string in that case.
Assuming your separator is '...', but it can be any string.
text = 'some string... this part will be removed.'
head, sep, tail = text.partition('...')
>>> print head
some string
If the separator is not found, head
will contain all of the original string.
The partition function was added in Python 2.5.
S.partition(sep)
->(head, sep, tail)
Searches for the separator sep in S, and returns the part before it, the separator itself, and the part after it. If the separator is not found, returns S and two empty strings.
If you want to remove everything after the last occurrence of separator in a string I find this works well:
<separator>.join(string_to_split.split(<separator>)[:-1])
For example, if string_to_split
is a path like root/location/child/too_far.exe
and you only want the folder path, you can split by "/".join(string_to_split.split("/")[:-1])
and you'll get
root/location/child
Without a regular expression (which I assume is what you want):
def remafterellipsis(text):
where_ellipsis = text.find('...')
if where_ellipsis == -1:
return text
return text[:where_ellipsis + 3]
or, with a regular expression:
import re
def remwithre(text, there=re.compile(re.escape('...')+'.*')):
return there.sub('', text)
If you love us? You can donate to us via Paypal or buy me a coffee so we can maintain and grow! Thank you!
Donate Us With