Communities for your favorite technologies. Explore all Collectives
Stack Overflow for Teams is now called Stack Internal. Bring the best of human thought and AI automation together at your work.
Bring the best of human thought and AI automation together at your work. Learn more
Find centralized, trusted content and collaborate around the technologies you use most.
Stack Internal
Knowledge at work
Bring the best of human thought and AI automation together at your work.
I have a string with two "-"
467.2-123-hdxdlfow
I want to remove everything after the second "-" so that I get "467.2-123". What is the best way to do this?
before, sep, after = theString.rpartition("-")
This splits the str about the last occurrence of "-" and your answer would be the variable before.
before
Add a comment
In [6]: "-".join('467.2-123-hdxdlfow'.split('-')[0:2]) Out[6]: '467.2-123'
>>> s = '467.2-123-hdxdlfow' >>> s[:s.rfind('-')] '467.2-123'
If you are after everything but the last element, I have modifed spicavigo's answer to exclude the last element.
a='467.2-123-hdxdlfow' '-'.join(a.split('-')[:-1])
a='467.2-123-hdxdlfow' '-'.join(a.split('-')[:2])
If you have exactly 2 '-', you could do
a.rsplit('-',1)[0]
Try this regex
([^-]*-[^-]*)-.*
and ask the result for the first capturing group ((...) in the example).
(...)
You can try this result = re.sub("([^-]*-[^-]*)(-.*$)", r"\1", '467.2-123-hdxdlfow') gives 467.2-123
result = re.sub("([^-]*-[^-]*)(-.*$)", r"\1", '467.2-123-hdxdlfow')
467.2-123
Required, but never shown
By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.
Start asking to get answers
Find the answer to your question by asking.
Explore related questions
See similar questions with these tags.