How to remove all characters after a specific character in python?
--
Music by Eric Matyas
https://www.soundimage.org
Track title: Forest of Spells Looping
--
Chapters
00:00 Question
00:30 Accepted answer (Score 376)
00:53 Answer 2 (Score 129)
01:39 Answer 3 (Score 30)
02:19 Answer 4 (Score 11)
02:42 Thank you
--
Full question
https://stackoverflow.com/questions/9047...
Accepted answer links:
[Alex's solution]: https://stackoverflow.com/a/904753/45183...
Answer 2 links:
[partition]: https://docs.python.org/3/library/stdtyp...
--
Content licensed under CC BY-SA
https://meta.stackexchange.com/help/lice...
--
Tags
#python #replace
#avk47
ACCEPTED ANSWER
Score 405
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.
ANSWER 2
Score 141
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.
ANSWER 3
Score 34
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
ANSWER 4
Score 11
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)